简体   繁体   English

用索引数组对列表进行排序的最佳方法

[英]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: 使用Java 8,您可以使用索引流和map()方法来实现:

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. 您可以使用SortedMap将整数映射到字符串值。 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() . 如果您打算按字母顺序对字符串进行排序,则可以使用Collections#sort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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