问题
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