This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Java 8 List <K, V>
I want to convert a List object to a Map using Streams and lambdas in Java 8
Here’s how I did it in Java 7
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;
}
Copy the code
I can easily do it with Java8 and Guava, but I don’t know how to do it without Guava
Guava writing:
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, new Function<Choice, String>() {
@Override
public String apply(final Choice input) {
returninput.getName(); }}); }Copy the code
Guava +Java 8 lambdas
private Map<String, Choice> nameMap(List<Choice> choices) {
return Maps.uniqueIndex(choices, Choice::getName);
}
Copy the code
Answer a:
Based on the Collectors documentation, it can be abbreviated to:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
Copy the code
Answer two
If your key is not guaranteed to be unique for every element in every list, you should convert it to Map<String, list > instead of Map<String, Choice>
Map<String, List<Choice>> result =
choices.stream().collect(Collectors.groupingBy(Choice::getName));
Copy the code
Answer three
Use getName() as the key and Choice itself as the map value:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));
Copy the code
Answer four
One thing most of the answers above miss is when a list has duplicate elements. IllegalStateException is thrown in this case. See the code below to handle duplicate list elements
public Map<String, Choice> convertListToMap(List<Choice> choices) {
return choices.stream()
.collect(Collectors.toMap(Choice::getName, choice -> choice,
(oldValue, newValue) -> newValue));
}
Copy the code
Answer five
For example, if you want to convert some fields of an object to a map:
Object is:
class Item{
private String code;
private String name;
public Item(String code, String name) {
this.code = code;
this.name = name;
}
//getters and setters
}
Copy the code
The operation of converting a List to a Map is as follows:
List<Item> list = new ArrayList<>();
list.add(new Item("code1"."name1"));
list.add(new Item("code2"."name2"));
Map<String,String> map = list.stream()
.collect(Collectors.toMap(Item::getCode, Item::getName));
Copy the code
The article translated from Stack Overflow:stackoverflow.com/questions/2…