是否有收集到订单保留集的收集器? [英] Is there a Collector that collects to an order-preserving Set?

查看:90
本文介绍了是否有收集到订单保留集的收集器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Collectors.toSet()不保留顺序。我可以使用Lists代替,但我想表明结果集合不允许元素重复,这正是 Set 接口的用途。

Collectors.toSet() does not preserve order. I could use Lists instead, but I want to indicate that the resulting collection does not allow element duplication, which is exactly what Set interface is for.

推荐答案

您可以使用 toCollection 并提供所需集合的具体实例。例如,如果您想保留广告订单:

You can use toCollection and provide the concrete instance of the set you want. For example if you want to keep insertion order:

Set<MyClass> set = myStream.collect(Collectors.toCollection(LinkedHashSet::new));

例如:

public class Test {    
    public static final void main(String[] args) {
        List<String> list = Arrays.asList("b", "c", "a");

        Set<String> linkedSet = 
            list.stream().collect(Collectors.toCollection(LinkedHashSet::new));

        Set<String> collectorToSet = 
            list.stream().collect(Collectors.toSet());

        System.out.println(linkedSet); //[b, c, a]
        System.out.println(collectorToSet); //[a, b, c]
    }
}

这篇关于是否有收集到订单保留集的收集器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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