Sorting a list based on another list's values - Java

后端 未结 5 969
梦如初夏
梦如初夏 2020-12-10 18:58

One list with names:(unsorted) e.g [paul, foul, mark]

Another list with integers: e.g [5, 2, 6]

The values on the secon

5条回答
  •  执念已碎
    2020-12-10 19:28

    Create a temporary mapping name->number, then sort names with custom comparator which uses the mapping:

    Map m = new HashMap;
    for(int i = 0; i < Names.size(); i++)
        m.put(Names.get(i), results.get(i));
    Collections.sort(Names, new Comparator() {
        @Override
        public int compare(String s1, s2) { return m.get(s2) - m.get(s1); }
    });
    

    This solution will work even if some numbers are equal.

提交回复
热议问题