Grouping list of objects where each object is 2 elements array

南笙酒味 提交于 2021-02-11 13:01:53

问题


List<Object[]> values =  query.getResultList();
    //values = [obj1,obj2,obj3]
    //obj1 = "1", "01";
    //obj2 = "1", "02";
    //obj3 = "1:, "03";

Map<String, List<String>> resultMap = values.stream().collect(Collectors.groupingBy(???));

I need a map grouped as - {"1",["01","02","03"]}

I have seen few references but nothing seems to work. what should i put in place of "???" ? if you need anything else , kindly comment. Thanks in advance.

ref :

Shortcut for adding to List in a HashMap

groupingby list of arrays


回答1:


If your object[] is the string[].I think the code is this:

package com.test.dal;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LTest {

    public static void main(String[] args) {
        List<String[]> values = getResultList();
        //values = [obj1,obj2,obj3]
        //obj1 = "1", "01";
        //obj2 = "1", "02";
        //obj3 = "1:, "03";

        Map<String, List<String>> resultMap = values.stream().collect(Collectors.groupingBy(o -> ((String[]) o)[0], Collectors.mapping(o -> ((String[]) o)[1], Collectors.toList())));
        System.out.println(resultMap);
    }

    public static List<String[]> getResultList() {
        String[][] inits = {
                {
                        "1", "01"
                }, {
                "1", "02"
        }, {
                "1", "03"
        }
        };
        List<String[]> tbList = Arrays.asList(inits);
        return tbList;
    }
}


来源:https://stackoverflow.com/questions/63806012/grouping-list-of-objects-where-each-object-is-2-elements-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!