import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListGroupByFieldTest {
public static void main(String[] args) {
List<LaneParamVO> laneParamVOList = new ArrayList<>();
LaneParamVO laneParamVO = new LaneParamVO();
laneParamVO.setParamKey("p1");
laneParamVO.setParamValue("v1");
laneParamVO.setGroupId(1);
LaneParamVO laneParamVO1 = new LaneParamVO();
laneParamVO1.setParamKey("p2");
laneParamVO1.setParamValue("v2");
laneParamVO1.setGroupId(1);
LaneParamVO laneParamVO2 = new LaneParamVO();
laneParamVO2.setParamKey("p3");
laneParamVO2.setParamValue("v3");
laneParamVO2.setGroupId(2);
LaneParamVO laneParamVO3 = new LaneParamVO();
laneParamVO3.setParamKey("p4");
laneParamVO3.setParamValue("v4");
laneParamVO3.setGroupId(2);
laneParamVOList.add(laneParamVO);
laneParamVOList.add(laneParamVO1);
laneParamVOList.add(laneParamVO2);
laneParamVOList.add(laneParamVO3);
// java8流式写法
if (CollectionUtils.isNotEmpty(laneParamVOList)) {
Map<Integer, List<LaneParamVO>> collect = laneParamVOList.stream().collect(Collectors.groupingBy(LaneParamVO::getGroupId));
System.out.println(JSONObject.toJSONString(collect));
}
Map<Integer, List<LaneParamVO>> integerListMap = listGroup2MapTwo(laneParamVOList);
System.out.println(JSONObject.toJSONString(integerListMap));
}
/**
* java8之前的写法
* @param list
* @return
*/
private static Map<Integer, List<LaneParamVO>> listGroup2MapTwo(List<LaneParamVO> list) {
Map<Integer, List<LaneParamVO>> userSignSerialMap = Maps.newConcurrentMap();
if (CollectionUtils.isNotEmpty(list)) {
// 分组
for (LaneParamVO vo : list) {
Integer groupId = vo.getGroupId();
List<LaneParamVO> tempList = userSignSerialMap.get(groupId);
/*如果取不到数据,那么直接new一个空的ArrayList**/
if (tempList == null) {
tempList = Lists.newArrayList();
tempList.add(vo);
userSignSerialMap.put(groupId, tempList);
}
else {
/*某个vo之前已经存放过了,则直接追加数据到原来的List里**/
tempList.add(vo);
}
}
}
return userSignSerialMap;
}
}
输出:
{1:[{"groupId":1,"paramKey":"p1","paramValue":"v1"},{"groupId":1,"paramKey":"p2","paramValue":"v2"}],2:[{"groupId":2,"paramKey":"p3","paramValue":"v3"},{"groupId":2,"paramKey":"p4","paramValue":"v4"}]} {1:[{"groupId":1,"paramKey":"p1","paramValue":"v1"},{"groupId":1,"paramKey":"p2","paramValue":"v2"}],2:[{"groupId":2,"paramKey":"p3","paramValue":"v3"},{"groupId":2,"paramKey":"p4","paramValue":"v4"}]}
|