0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

List<Map<T1, T2>> を Map<T1, List<T2>> へ変換 (Stream API)

Last updated at Posted at 2016-10-12

ほぼ自分のメモ

概要

MyBatisとかでselectした時にresultTypeをMapにして結果が複数だとList<Map>の形式に戻ってくる。
ここから特定カラムの値リストだけ取りたいとか、そういう要望があって
うまい具合にListにネストされたMapを出して、Map<key, List<value>> 形式にしたい。

ソース

わりとgenericsで悩まされる


public class Main {
    public static void main(String[] args) {

        List<Map<String, String>> list = new ArrayList<>();
        list.add(new HashMap<String, String>() {{
            put("a1", "test1");
            put("a2", "test2");
            put("b1", "testb1");
            put("b2", "testb2");
        }});
        list.add(new HashMap<String, String>() {{
            put("a1", "test3");
            put("a2", "test4");
            put("b1", "testb4");
            put("b2", "testb3");
        }});
        list.add(new HashMap<String, String>() {{
            put("a1", "test5");
            put("a2", "test6");
            put("b1", "testb8");
            put("b2", "testb9");
        }});

        Map<String, List<String>> map = list.stream()
                .flatMap(e -> e.entrySet().stream())
                .collect(Collectors.groupingBy(
                        Map.Entry::getKey,
                        Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

        List<String> a1list = map.get("a1");
        System.out.println(a1list.toString());

    }
}


説明は省略

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?