简体   繁体   中英

Best way to sort list with index array

I would like to sort a list of strings with an array of integers as the new indexes:

Integer[] newIndexes = {0,2,1};
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Pear");
fruits.add("Banana");
fruits.sort....

What would be the best way to do this?

Using Java 8, you can do it using a stream of the indexes and the map() method:

List<String> sortedFruits = Stream.of(newIndexes).map(fruits::get).collect(Collectors.toList());

gives the list

[Apple, Banana, Pear]

You can use a SortedMap to map the integers to the string values. This way it will sort the string values according to the natural ordering of the keys:

SortedMap<Integer, String> map = new TreeMap<Integer, String>();
for (int i = 0; i < newIndexes.length; i++) {
    map.put(newIndexes[i], fruits.get(i));
}

Collection<String> sortedFruits = map.values();

If you intend to sort the strings alphabetically, then you can just use Collections#sort() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM