加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

lambda – 将字符串列表转换为已排序的Map字符串长度作为键

发布时间:2020-12-15 05:14:37 所属栏目:Java 来源:网络整理
导读:我有一个List String并且我必须将它转换为Map,通过将相同长度的字符串分组到List中,使用字符串长度作为键,排序顺序.它可以使用 – MapInteger,ListString result = new TreeMap();for (String str : list) { if (!result.containsKey(str.length())) { resul
我有一个List< String>并且我必须将它转换为Map,通过将相同长度的字符串分组到List中,使用字符串长度作为键,排序顺序.它可以使用 –

Map<Integer,List<String>> result = new TreeMap<>();
for (String str : list) {
    if (!result.containsKey(str.length())) {
        result.put(str.length(),new ArrayList<>());
    }
    result.get(str.length()).add(str);
}

我们怎样才能使用Java 8流?

解决方法

你可以用流做:

Map<Integer,List<String>> result = list.stream()
    .collect(Collectors.groupingBy(
        String::length,// use length of string as key
        TreeMap::new,// create a TreeMap
        Collectors.toList())); // the values is a list of strings

这通过接受3个参数的Collectors.groupingBy的重载来收集流:关键映射器函数,映射的提供者和下游收集器.

但是,有一种更简洁的方法,没有流:

Map<Integer,List<String>> result = new TreeMap<>();
list.forEach(s -> result.computeIfAbsent(s.length(),k -> new ArrayList<>()).add(s));

这使用List.forEachMap.computeIfAbsent来实现你想要的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读