将String列表转换为已排序的Map String length作为键 [英] Convert String list to sorted Map String length as key

查看:130
本文介绍了将String列表转换为已排序的Map String length作为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表< String> ,我必须将它转换为 Map ,通过分组相同的长度 String 进入 List ,使用 String length作为密钥in,排序顺序。它可以使用 -

I have a List<String> and I have to convert it to Map, by grouping same length Strings into a List, using String length as the key in, sorted order. It can be done using -

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流做到这一点?

How can we do it using Java 8 streams?

推荐答案

你可以用流来做:

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个参数:键映射函数,映射的供应商和/或下游收集器。

This collects the stream by means of the overload of Collectors.groupingBy that accepts 3 arguments: the key mapper function, the supplier of the map and the downstream collector.

但是,有一种更紧凑的方式,没有流:

However, there's a more compact way to do it, without streams:

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

这使用 List.forEach Map.computeIfAbsent 实现您的目标。

This uses List.forEach and Map.computeIfAbsent to achieve what you want.

这篇关于将String列表转换为已排序的Map String length作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆