Java ArrayList sort two lists in same order

rainer :

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?

Danyal Sandeelo :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87252&siteId=1