Java 8:从Collections中删除Collections.toMap()。如何保持秩序? [英] Java 8 : streams Collections.toMap() from List . How to keep the order?

查看:1435
本文介绍了Java 8:从Collections中删除Collections.toMap()。如何保持秩序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从列表创建一个地图如下:

I am creating a Map from a List as follows :

Map<String,ItemVariant> map = itemExt.getVariants().stream().map((extVar)->{
                                                                 //convert Variant
                                                                 ItemVariant itemVar = conversionService.convert(extVar, ItemVariant.class);
                                                                 return itemVar;
                                                               }).collect(Collectors.toMap(ItemVariant::getSku, Function.<ItemVariant>identity()));

我想保持与List中相同的顺序:itemExt.getVariants()

I want to keep the same order as in the List: itemExt.getVariants()

如何使用这些Collectors.toMap()函数创建LinkedHashMap?

How to create a LinkedHashMap using these Collectors.toMap() functions ?

推荐答案

Collectors.toMap()的2个参数版本执行以下操作:

The 2 parameter version of Collectors.toMap() does the following:

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);
}

因此您可以替换:

Collectors.toMap(ItemVariant::getSku, Function.<ItemVariant>identity())

与:

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

new toLinkedMap()方法:

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

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);
    }
}

并使用它。

这篇关于Java 8:从Collections中删除Collections.toMap()。如何保持秩序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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