JavaBeanのList
があって、Beanのあるフィールドがキー、Beanが値なMap
を作りたいとき。よくある。
GuavaのMaps.uniqueIndex
を使うと楽。
こういうデータがあって、
@lombok.Data
@lombok.AllArgsConstructor
public class Foo {
private Integer id;
private String name;
}
こういうリストがあるとすると、
List<Foo> fooList = Arrays.asList(new Foo(1, "aaa"), new Foo(2, "bbb"), new Foo(3, "ccc"));
com.google.common.collect.Maps#uniqueIndex(java.lang.Iterable<V>, com.google.common.base.Function<? super V,K>)
を使う
Map<Integer, Foo> fooMap = Maps.uniqueIndex(fooList, Foo::getId);
System.out.println(fooMap);
出力結果は
{1=ParticipantsTest.Foo(id=1, name=aaa), 2=ParticipantsTest.Foo(id=2, name=bbb), 3=ParticipantsTest.Foo(id=3, name=ccc)}
返りのMapはcom.google.common.collect.ImmutableMap
で不変です。
GuavaとLambda式の相性いいな〜。
2014-09-21 追記
Stream APIで普通に出来た・・
Map<Integer, Foo> fooMap = fooList.stream().collect(Collectors.toMap(Foo::getId, Function.identity()));
System.out.println(fooMap);
恥ずい・・