LoginSignup
1
0

More than 5 years have passed since last update.

streamを学んだ(ListをMap<Integer,List>に変換したい)

Posted at

List形式のデータをMap>形式に変換する

今まで愚直にfor使っていたので、メモ。

DBから取得した、リスト形式のデータを
フィルタリングした上で、Map形式に変換したい(そのほうがjspで表示するときに楽だった)なと思った時に使った。

List<myClass> resList = myClassDao.query(insMap);

// フィルタリング
List<myClass> dataList = resList.stream()
        .filter(c -> c.getHogeId() != null)
        .collect(Collectors.toList());

// Mapに変換
Map<Integer, List<myClass>> res = dataList.stream().collect(
        Collectors.groupingBy(myClass::getHogeId)
);

これで、こんな感じのデータが

[
    {
        id:1,
        hogeId:1,
        data:"a"
    },
    {
        id:2,
        hogeId:1,
        data:"b"
    },
    {
        id:3,
        hogeId:2,
        data:"c"
    },
    {
        id:4,
        hogeId:null,
        data:"d"
    }
]

こうなります。多分。

{
    1:[
        {
            id:1,
            hogeId:1,
            data:"a"
        },
        {
            id:2,
            hogeId:1,
            data:"b"
        }
    ],
    2:[
        {
            id:3,
            hogeId:2,
            data:"c"
        }
    ]
}

もっといいやり方があればぜひ教えてください!

1
0
2

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
1
0