问题描述
由Maurice Naftalin掌握Lambdas,第6章 - 流性能。
Mastering Lambdas by Maurice Naftalin, Ch6 - Stream Performance.
有关不同执行阶段的流的不同特征的解释(中间和终端) 。
例如。
There is explanation about the different characteristics of streams at the different stages of execution(intermediate & terminal).For eg.
Stream.of(8,3,5,6,7,4)//ORDERED, SIZED
.filer(i->i%2==0) // ORDERED
.sorted() // ORDERED, SORTED
.distinct() // DISTINCT, ORDERED, SORTED
.map(i->i+1) // ORDERED
.unordered(); //none
令我困惑的是对SORTED特征的解释:
What was confusing to me was explanation of SORTED characteristics :
如果已经为此目的定义并使用了比较器,则流元素可能已按其他顺序排序,但此类流不具有SORTED特征。
为什么如果提供自定义比较器来实现排序数据结构(在上面的情况下为SortedMap),框架不会考虑创建具有SORTED特性的流?
Why if the custom comparator is provided for the implementation of Sorted Data Structure(SortedMap in above case) the framework would not consider creating streams with SORTED characteristic?
推荐答案
在他的评论中,飞行是完全正确的。 SORTED
仅针对自然顺序报告,之前已经进行过辩论。首先,这甚至在内部用作标志: isNaturalSort
:
Flown is absolutely correct in his comment. SORTED
is only reported for natural order and this has been debated before. First this is even internally used as a flag called: isNaturalSort
:
/**
* Sort using natural order of {@literal <T>} which must be
* {@code Comparable}.
*/
OfRef(AbstractPipeline<?, T, ?> upstream) {
super(upstream, StreamShape.REFERENCE,
StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED);
this.isNaturalSort = true;
相同的标志 isNaturalSort
设置为 false
当通过使用时排序(CustomComparator)
。
The same flag isNaturalSort
is set to false
when used via sorted(CustomComparator)
.
这个是一个内部的细节,似乎jdk开发人员并没有找到有用的实现它 - 可能与它无关,可能真的很有用。但这可能会改变......
This is an internal details and it seems that the jdk developers did not find useful to implemented it as such - there was probably nothing to do with it that could be really useful. But this might change...
这里至少存在一个漏洞。想象一下这样的一个类:
There is at least one flaw here still. Imagine a class like this:
static class User implements Comparable<User> {
private final int id;
public User(int id) {
super();
this.id = id;
}
public int getId() {
return id;
}
@Override
public int compareTo(User usr) {
return 42; // don't do this
}
}
以及一些流操作:
Stream<User> byId = Stream.of(new User(12), new User(10))
.sorted(Comparator.comparing(User::getId));
System.out.println(byId.spliterator().hasCharacteristics(Spliterator.SORTED));
Stream<User> natural = Stream.of(new User(12), new User(10))
.sorted(Comparator.naturalOrder());
System.out.println(natural.spliterator().hasCharacteristics(Spliterator.SORTED));
Stream<User> plain = Stream.of(new User(12), new User(10)).sorted();
System.out.println(plain.spliterator().hasCharacteristics(Spliterator.SORTED));
前两个报告 false
,但是最后一个报告 true
;这至少怪异。
The first two report false
, but the last one reports true
; which is at least weird.
这篇关于如果使用自定义Comparator创建,则为SortedMap生成的流的流特征可能不会被分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!