将字符串列表转换为已排序的映射字符串长度作为键

阿披耶·斯里瓦斯塔瓦(Abhijeet srivastava)

我有一个List<String>,我必须Map通过将相同的长度Strings分组,将长度转换为List,将String长度作为键,并按排序顺序进行转换。可以使用-

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

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

但是,有一种更紧凑的方式来执行此操作,而无需使用流:

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

使用List.forEachMap.computeIfAbsent实现您想要的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python将未知长度的(字符串)元组转换为字符串列表

如何将列表作为字符串从API转换为字符串列表

将字符串转换为字符串列表

将整数列表转换为字符串,作为排序中dict的键

将映射字符串字符串转换为映射字符串列表字符串-Java 7

scala将字符串列表转换为键/值映射

C# - 将字符串数组转换为字符串列表

C-将字符串(句子)转换为字符串列表

熊猫-将字符串转换为字符串列表

将字符串列表转换为逗号分隔的字符串,而不重复

JAVA将字符串列表转换为字符串数组

如何将字符串转换为字符串列表?

将字符串列表转换为单个字符串

Ocaml 将字符串列表转换为字符串

添加新字符串时,将单个字符串转换为字符串列表

将列表列表转换为字符串列表

将列表(对象)列表转换为字符串列表

将字符串或列表的映射转换为值的字符串或逗号分隔的值

Java 8 将字符串列表的列表转换为映射

按字符串长度降序对字符串列表进行排序,请勿更改列表

按字符串长度降序对字符串列表进行排序,不会更改列表

将元组字符串列表转换为元组列表

Python将字符串列表转换为列表

将列表转换为字符串列表

将字符串列表转换为整数列表

将字符串列表转换为浮动列表

将字符串列表转换为python中的列表

Python将字符串列表转换为元组列表

将列表转换为字符串列表python