JAVA lambda分组
public static void main(String[] args) { List<Map<String,Object>> list = new ArrayList<>(); Map<String,Object> map1 = new HashMap<String, Object>(); map1.put("stockCode","000001.SZ"); map1.put("stockName","平安银行"); map1.put("traddate","2023-06-07"); Map<String,Object> map2 = new HashMap<String, Object>(); map2.put("stockCode","000002.SZ"); map2.put("stockName","万科A"); map2.put("traddate","2023-06-07"); Map<String,Object> map3 = new HashMap<String, Object>(); map3.put("stockCode","000002.SZ"); map3.put("stockName","万科A"); map3.put("traddate","2023-06-08"); list.add(map1); list.add(map2); list.add(map3); //通过股票去重该list中某个key并存储到list中 List<Object> distinctStockList = list.stream().map(m -> m.get("stockCode")).distinct().collect(Collectors.toList()); System.err.println("去重后股票列表为===" + distinctStockList.toString()); //通过股票分组该list Map<Object, List<Map<String, Object>>> stockCollect = list.stream().collect(Collectors.groupingBy(m -> m.get("stockCode"))); for (int i = 0; i < distinctStockList.size(); i++) { List<Map<String, Object>> listByStock = stockCollect.get(distinctStockList.get(i)); System.err.println("根据单个股票输出===" + listByStock.toString()); } }
打印输出为:
去重后股票列表为===[000001.SZ, 000002.SZ] 根据单个股票输出===[{stockName=平安银行, traddate=2023-06-07, stockCode=000001.SZ}] 根据单个股票输出===[{stockName=万科A, traddate=2023-06-07, stockCode=000002.SZ}, {stockName=万科A, traddate=2023-06-08, stockCode=000002.SZ}]