0

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?

1
  • 2
    Just use a TreeMap<Integer, String>, put index and string and then get the values sorted by index. Commented Nov 14, 2014 at 12:34

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

sadly enough i have to use Java 7, still +1
0

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().

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.