2

I have a list of objects. I want to do the following

for (int i = 0; i < sorted.size(); i++) {
    map.put(i, sorted.get(i).getName());
}

Is there a straightforward way to do this in Java 8 streams api ?

0

2 Answers 2

2

You can do the following:

Map<Integer, String> map =
        IntStream.range(0, sorted.size())
                 .boxed()
                 .collect(toMap(i -> i, i -> sorted.get(i).getName()));

This creates a Stream of int going from 0 to the size of list and collects each value into a Map.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer, but i was hoping for something more like sorted.stream().blah(....)
You can't stream a list with its indexes, unfortunately, see this: stackoverflow.com/q/28989841/1743880
@dinesh707, EntryStream.of(sorted).mapValues(s -> s.getName()).toMap() using my free library if you really want not to think about indices. In general Tunaki solution is fine.
2

Since you want to collect the elements into a data structure which intrinsically tracks the position as its size, you can do the operation using a custom collector:

Map<Integer, String> map=sorted.stream()
    .map(x -> x.getName())
    .collect(HashMap::new, (m,s) -> m.put(m.size(), s),
        (a,b) -> { int off=a.size(); b.forEach((i,s) -> a.put(i+off, s));});

The trickiest part is the merge function which will be used in parallel processing only. It adds all elements of a map to its preceding map, but has to offset the keys by the number of preceding elements.

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.