首页 文章

是否有收集到订单保留集的收集器?

提问于
浏览
79

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

1 回答

  • 157

    您可以使用 toCollection 并提供所需集的具体实例 . 例如,如果要保留插入顺序:

    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]
        }
    }
    

相关问题