---
title: com.google.common.collect.MapsでListからMapに変換する
tags: ["Guava", "Java", "Java SE 8"]
categories: ["Programming", "Java", "com", "google", "common", "collect", "Maps"]
date: 2014-06-13T18:30:07Z
updated: 2014-09-20T21:36:19Z
---

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


恥ずい・・


<a href="http://www.amazon.co.jp/Getting-Started-With-Google-Guava/dp/1783280158%3FSubscriptionId%3DAKIAJ7Y2FDFBWLT5HCQA%26tag%3Dikam-22%26linkCode%3Dsp1%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1783280158"><img src="http://ecx.images-amazon.com/images/I/41p6Ucr9IxL._SL160_.jpg" title="Getting Started With Google Guava"></a>
