Reputation: 4694
I want to sort a stream and then collect its elements as their respective original indices.
E.g. for:
List<String> l = Arrays.asList("a", "b", "d", "c");
List<Integer> i = l.stream().sorted(Comparator.comparing(s -> s)).??? // what to do here?
// i = [0, 1, 3, 2]
Upvotes: 1
Views: 77
Reputation: 31978
You can use IntStream
:
List<Integer> i = IntStream.range(0,l.size())
.boxed()
.sorted(Comparator.comparing(l::get))
.collect(Collectors.toList());
Upvotes: 5