Java8-集合转其它格式

本文演示了Java中List的去重、转换为数组、转换为字符串以及利用Stream进行分组计数和排序的操作。通过`distinct()`实现去重,`toArray()`转为数组,`collect(joining())`生成字符串,`groupingBy()`与`counting()`组合用于统计频次,最后使用`LinkedHashMap`进行排序展示。
@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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值