IK.AM

@making's tech note


com.google.common.collect.MapsでListからMapに変換する

🗃 {Programming/Java/com/google/common/collect/Maps}
🏷 Guava 🏷 Java 🏷 Java SE 8 
🗓 Updated at 2014-06-13T18:30:07Z  🗓 Created at 2014-06-13T18:30:07Z   🌎 English Page

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);

恥ずい・・


✒️️ Edit  ⏰ History  🗑 Delete