1、利用stream對數據進行分組並求和
public static void main(String[] args) {
List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya");
// Map<String,Long> map = items.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
Map<String,Long> map = items.stream().collect(Collectors.groupingBy(t->t,Collectors.counting()));
System.out.println(JSON.toJSONString(map));
}
輸出結果:{"papaya":1,"orange":1,"banana":2,"apple":3}
2、
在實際需求中,我們可能需要對一組對象進行分組,而且分組的條件有多個。比如對國家和產品類型進行雙重分組,一種比較復雜的方法是先對產品類型進行分組,然后對每一個產品類型中的國際名進行分組求和。
轉換前的對象:
@Data
public class GameMusicVO implements Serializable {
/**
* 游戲Id
**/
private Integer gameId;
/**
* 音樂Id
**/
private Integer musicId;
/**
* 音樂code
**/
private String musicCode;
/**
* 音樂配置名稱
**/
private String codeName;
/**
* 音樂名稱
**/
private String musicName;
/**
* 音樂大小
**/
private Float size;
/**
* 音樂長度
**/
private Long timeLength;
/**
* 存儲的路徑
**/
private String path;
/**
* 是否選中
**/
private String value;
}
轉換后的格式:
@Data public class GameNewMusicVO implements Serializable { /** * 音樂code **/ private String code; /** * 音樂配置名稱 **/ private String codeName; /** * 音樂列表 **/ private List<GameMusicVO> children; }
轉換代碼:
List<GameMusicVO> musicList = new ArrayList<>(); //自己添加list Map<String, List<GameMusicVO>> menuGroupMap = musicList.stream().collect(Collectors.groupingBy(GameMusicVO::getMusicCode)); List<GameNewMusicVO> musicNewVOList = menuGroupMap.keySet().stream().map(key -> { GameNewMusicVO temp = new GameNewMusicVO(); temp.setCode(key);
//這里雖然code與codeName是一對一,但還需要再查詢一次。 //temp.setCodeName(GameStringUtils.matchCodeName(key,musicCodeVOList)); temp.setChildren(menuGroupMap.get(key)); return temp; }).collect(Collectors.toList());
優化代碼:
Map<String, List<GameMusicVO>> menuGroupMap = musicList.stream().collect(Collectors.groupingBy(v -> v.getMusicCode() + "_" + v.getMusicName()));
List<GameNewMusicVO> musicNewVOList = menuGroupMap.keySet().stream().map(key -> {
String[] keyArr = key.split("_");
String code = keyArr[0];
String codeName = keyArr[1];
GameNewMusicVO temp = new GameNewMusicVO();
temp.setCode(code);
temp.setCodeName(codeName);
temp.setChildren(menuGroupMap.get(key));
return temp;
}).collect(Collectors.toList());
