5

I have two ArrayLists in Java. Both lists are unsorted.

    ArrayList<Integer> listOne = new ArrayList<>();
    listOne.add(2);
    listOne.add(1);
    listOne.add(4);
    listOne.add(8);
    listOne.add(6);

    ArrayList<String> listTwo = new ArrayList<>();
    listTwo.add("ant");
    listTwo.add("bear");
    listTwo.add("cat");
    listTwo.add("dog");
    listTwo.add("zebra");

I want to sort listOne in natural order and each item of listTwo should be sorted according to the position in listOne:

What I have so far is:

  Collections.sort(listOne);

  for (int i = 0; i < listOne.size(); i++) {

        int intTest = listOne.get(i);
        String stringTest = listTwo.get(i);

        System.out.println(intTest);
        System.out.println(stringTest);

    }

This prints :

  1 ant, 2 bear, 4 cat , 6 dog , 8 zebra

My expected print output is:

  1 bear, 2 ant, 4 cat, 6 zebra, 8 dog

So that when the item of listOne "1", that changed the position from 2nd to 1st, the item "bear" in listTwo, that was on the 2nd position, should also print on the 1st position.

What would be the most simple and efficient way to do this?

6
  • 10
    Just don't use two lists. Use a single list of objects, where each object has a numeric value and an animal name. Java is an OO language. use classes and objects. Commented Mar 27, 2019 at 12:54
  • 4
    If you really do not want to use classes and objects as JB Nizet mentioned, use a Map instead of a List Commented Mar 27, 2019 at 12:56
  • 2
    use Map<Integer,String> Commented Mar 27, 2019 at 12:56
  • 1
    possible duplicate of stackoverflow.com/questions/49034985/… Commented Mar 27, 2019 at 13:00
  • 1
    Creating classes is fundamental stuff, covered by any tutorial or introductory book about Java. Sorting objects can be done by googling for "how to sort ojects in Java". Please, do some research. You'll learn a lot more doing that than by copying and pasting my code. Commented Mar 27, 2019 at 13:07

5 Answers 5

4

Create an ordered list of indices:

int n = listOne.size();
assert n == listTwo.size();

Integer[] indices = new Integer[n];
for (int i = 0; i < n; ++i) {
  indices[i] = i;
}

Sort that list using a comparator that compares indices by looking at the corresponding elements in listOne.

Arrays.sort(
    indices,
    new Comparator<Integer>() {
      public int compare(Integer a, Integer b) {
        return listOne.get(a).compareTo(listOne.get(b));
      }
    });

Now you can use indices to reorder both lists:

static <T> void reorder(Integer[] indices, List<T> mutatedInPlace) {
  List<T> tempSpace = new ArrayList<T>(indices.length);
  for (int index : indices) {
    tempSpace.add(mutatedInPlace.get(index);
  }
  mutatedInPlace.clear();
  mutatedInPlace.addAll(tempSpace);
}

reorder(indices, listOne);
reorder(indices, listTwo);
Sign up to request clarification or add additional context in comments.

1 Comment

TreeMap best suits this situation. It inserts the data in sorted order so basically store the key and against each key you can store the animal.
2

TreeMap best suits this situation. It inserts the data in sorted order so basically store the key and against each key you can store the animal.

Map<Integer,String> sortedMap = new TreeMap<Integer,String>();
sortedMap.push(listOne.get(i),listTwo.get(listOne.get(i)));

In case you want to stick to ArrayList, you can iterate over the listOne and push it in HashMap<Integer,String>

iterate over list (for example i)
map.put( listOne.get(i), secondList.get(i));

So the hashMap would be like (2, "ant");

  • Collections.sort(listOne);
  • Against each entry, you can get the corresponding animal from map

3 Comments

I think you have to use SortedMap so there is no need to use Collections.sort
Instead of sorting separately, the OP can use treeMap, just need to iterate over the list and the OP would have the required data set in the treeMAP
Don't you need a SortedMultiMap in case listOne contains duplicates?
2

We can use HashMap data structure, It contains “key-value” pairs and allows retrieving the value by key.

int i = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

Here we’re storing the items from listOne as keys and their position as a value in the HashMap.

for (Integer num : listOne) {
        map.put(num, i);
        i++;
    }

We’re printing the elements from listTwo as per the items from the listOne changed their position.

Collections.sort(listOne);
    for (Integer num : listOne) {
        System.out.println(num + " " + listTwo.get(map.get(num)));
    }

One Solution:

    int i = 0;
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (Integer num : listOne) {
        map.put(num, i);
        i++;
    }
    Collections.sort(listOne);
    for (Integer num : listOne) {
        System.out.println(num + " " + listTwo.get(map.get(num)));
    }

Output is:

1 bear, 2 ant, 4 cat, 6 zebra, 8 dog

Comments

1

If you use a Map<Integer, String> for this, you don't even need to sort it if you take the TreeMap implementation.

It basically works as follows:

public class StackoverflowMain {

    public static void main(String[] args) {
        // initialize a map that takes numbers and relates Strings to the numbers
        Map<Integer, String> animals = new TreeMap<Integer, String>();
        // enter ("put" into the map) the values of your choice
        animals.put(2, "ant");
        animals.put(1, "bear");
        animals.put(4, "cat");
        animals.put(8, "dog");
        animals.put(6, "zebra");
        // print the whole map using a Java 8 forEach statement
        animals.forEach((index, name) -> System.out.println(index + ": " + name));
    }

}

This code will output

1: bear
2: ant
4: cat
6: zebra
8: dog

Comments

1

Putting the suggestions of all the friendly and helpful people together (plus some other research and test), here is the final code I came up with:

ArrayList<String> listOne = new ArrayList<>();
listOne.add("one");
listOne.add("eight");
listOne.add("three");
listOne.add("four");
listOne.add("two");

ArrayList<String> listTwo = new ArrayList<>();
listTwo.add("ant");
listTwo.add("bear");
listTwo.add("cat");
listTwo.add("dog");
listTwo.add("zebra");

Map<String, String> sortedMap = new TreeMap<String, String>();

for (int i = 0; i < listOne.size(); i++) {

    String stringkey = listOne.get(i);
    String stringValue = listTwo.get(i);

    sortedMap.put(stringkey, stringValue);
}

print output = {eight=bear, four=dog, one=ant, three=cat, two=zebra}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.