简体   繁体   English

带比较器的有序流

[英]ordered stream with comparator

Does getSortedUsers() always returns an orderd stream of getUsers() independent of the getUsers() -collection type? 是否getSortedUsers()总是返回的orderd流getUsers() 独立getUsers() -collection类型?

public Set<User> getUsers(){
    // unordered collection type
    HashSet<User> set = new HashSet<>();
    set.add(..);
    set.add(..);
    set.add(..);
    return set;
}

// Is the stream only sorted if getUsers() is hold within a sortable collection type?
public Stream<User> getSortedUsers(Comparator<User> comp){
    return getUsers().stream().sorted(comp);
}

The Stream returned by getSortedUsers() will always be sorted, which is guaranteed by the call to sorted(comp) . getSortedUsers()返回的Stream将始终进行排序,这可以通过对sorted(comp)的调用来保证。 It doesn't matter what's the source of the Stream . Stream的源是什么都没有关系。

Now, if you decide to collect the elements of that Stream into some Collection , the order may or may not be preserved, depending on which type of Collection you choose. 现在,如果您决定将该Stream的元素收集到某个Collection ,则顺序可能会保留,也可能不会保留,具体取决于您选择的Collection类型。 If you collect the elements into a HashSet , you'll lose the order. 如果将元素收集到HashSet ,则会失去顺序。 If you collect into a TreeSet , a LinkedHashSet or any List , you'll keep the order. 如果您收集到TreeSetLinkedHashSet或任何List ,则将保持顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM