在流上使用 Collections.toMap() 时如何保持 List 的迭代顺序? [英] How do I keep the iteration order of a List when using Collections.toMap() on a stream?

查看:14
本文介绍了在流上使用 Collections.toMap() 时如何保持 List 的迭代顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 List 创建一个 Map 如下:

I am creating a Map from a List as follows:

List<String> strings = Arrays.asList("a", "bb", "ccc");

Map<String, Integer> map = strings.stream()
    .collect(Collectors.toMap(Function.identity(), String::length));

我想保持与 List 中相同的迭代顺序.如何使用 Collectors.toMap() 方法创建 LinkedHashMap?

I want to keep the same iteration order as was in the List. How can I create a LinkedHashMap using the Collectors.toMap() methods?

推荐答案

2 参数版本的 Collectors.toMap() 使用 HashMap:

public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(
    Function<? super T, ? extends K> keyMapper, 
    Function<? super T, ? extends U> valueMapper) 
{
    return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}

要使用 4参数版本,可以替换:

Collectors.toMap(Function.identity(), String::length)

与:

Collectors.toMap(
    Function.identity(), 
    String::length, 
    (u, v) -> {
        throw new IllegalStateException(String.format("Duplicate key %s", u));
    }, 
    LinkedHashMap::new
)

或者为了更简洁,编写一个新的 toLinkedMap() 方法并使用它:

Or to make it a bit cleaner, write a new toLinkedMap() method and use that:

public class MoreCollectors
{
    public static <T, K, U> Collector<T, ?, Map<K,U>> toLinkedMap(
        Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper)
    {
        return Collectors.toMap(
            keyMapper,
            valueMapper, 
            (u, v) -> {
                throw new IllegalStateException(String.format("Duplicate key %s", u));
            },
            LinkedHashMap::new
        );
    }
}

这篇关于在流上使用 Collections.toMap() 时如何保持 List 的迭代顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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