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); }
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.
The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed: List of values and. List of keys from a Map.
Based on Collectors
documentation it's as simple as:
Map<String, Choice> result = choices.stream().collect(Collectors.toMap(Choice::getName, Function.identity()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With