すぐ忘れるのでメモ。
idが重複するとjava.lang.IllegalStateException: Duplicate key
が発生するので注意。
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
public class ListToMapSample {
public static void main(String[] args) {
List<Foo> fooList = new ArrayList<>();
fooList.add(new Foo(123, "aiueo"));
fooList.add(new Foo(234, "ateawgareg"));
fooList.add(new Foo(456, "faaewfgwaiaef"));
Map<Integer, Foo> map = fooList.stream()
.collect(Collectors.toMap(Foo::getId, UnaryOperator.identity()));
System.out.println(map);
}
private static class Foo {
private int id;
private String name;
public Foo(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String toString() {
return "{id:" + id + ", name:" + name + "}";
}
}
}
{456={id:456, name:faaewfgwaiaef}, 234={id:234, name:ateawgareg}, 123={id:123, name:aiueo}}