Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (2.6k points)

I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below.

private Map<String, Choice> nameMap(List<Choice> choices)

{ final Map<String, Choice> hashMap = new HashMap<>();

for (final Choice choice : choices)

{ hashMap.put(choice.getName(), choice); }

return hashMap; }

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

private Map<String, Choice> nameMap(List<Choice> choices)

{ return Maps.uniqueIndex(choices, new Function<Choice, String>()

{ @Override public String apply(final Choice input)

{ return input.getName(); } });

}

And Guava with Java 8 lambdas.

private Map<String, Choice> nameMap(List<Choice> choices) { return Maps.uniqueIndex(choices, Choice::getName);

}

1 Answer

0 votes
by (46k points)

To translate a List of objects into a Map using Java 8's streams and lambdas use collectors

Map<String, Choice> result =

 choices.stream().collect(Collectors.toMap(Choice::getName, 

Function.identity()));

Click here to read about the collector. 

Related questions

0 votes
1 answer
asked Jun 20, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...