Nick Russler
Nick Russler

Reputation: 4694

Map stream to list of original indices

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

Answers (1)

Naman
Naman

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

Related Questions