@Test
public void ListToOthers() throws Exception {
List<String> idsList = Arrays.asList("4", "2", "2", "3", "4", "1");
// List 字符串 虑重
List<String> distinctStr = idsList.stream().distinct().collect(Collectors.toList());
System.out.println("List 字符串 虑重 = " + distinctStr);
// list 集合转化为array数组
String[] listToAArray = idsList.stream().toArray(String[]::new);
System.out.println("list 集合转化为array数组 = " + listToAArray);
// list 集合转化为String 字符串
String listToStr = idsList.stream().collect(Collectors.joining(","));
System.out.println("list 集合转化为String 字符串 = " + listToStr);
// list 集合转化为map分组计数
Map<String, Long> mapResult = idsList.stream().collect(groupingBy(Function.identity(), counting()));
// 排序
Map<String, Long> finalMap = new LinkedHashMap<>();
mapResult.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));
System.out.println("finalMap排序 = " + finalMap);
}
Java8-集合转其它格式
于 2021-01-15 15:13:28 首次发布
本文演示了Java中List的去重、转换为数组、转换为字符串以及利用Stream进行分组计数和排序的操作。通过`distinct()`实现去重,`toArray()`转为数组,`collect(joining())`生成字符串,`groupingBy()`与`counting()`组合用于统计频次,最后使用`LinkedHashMap`进行排序展示。

被折叠的 条评论
为什么被折叠?



