概述
本篇博客,主要是解决Lambda表达式九:Stream流三:Stream常用方法;的一个模糊的点,是对那篇文章中的一个补充。
本篇博客没什么,主要就是加深下对Comparator接口的了解。
目录
1.Stream接口的sorted()方法,Comparator函数式接口效果展示;
2.Comparetor函数式接口的简述(本部分转载自8.函数式接口Comparator)
1.Stream接口的sorted()方法,Comparator函数式接口效果展示;
Comparator接口中的核心方法,compare方法源码内容:
/**
* Compares its two arguments for order. Returns a negative integer,
* zero, or a positive integer as the first argument is less than, equal
* to, or greater than the second.<p>
*
* In the foregoing description, the notation
* <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
* <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
* <tt>0</tt>, or <tt>1</tt> according to whether the value of
* <i>expression</i> is negative, zero or positive.<p>
*
* The implementor must ensure that <tt>sgn(compare(x, y)) ==
* -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
* implies that <tt>compare(x, y)</tt> must throw an exception if and only
* if <tt>compare(y, x)</tt> throws an exception.)<p>
*
* The implementor must also ensure that the relation is transitive:
* <tt>((compare(x, y)>0) && (compare(y, z)>0))</tt> implies
* <tt>compare(x, z)>0</tt>.<p>
*
* Finally, the implementor must ensure that <tt>compare(x, y)==0</tt>
* implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all
* <tt>z</tt>.<p>
*
* It is generally the case, but <i>not</i> strictly required that
* <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking,
* any comparator that violates this condition should clearly indicate
* this fact. The recommended language is "Note: this comparator
* imposes orderings that are inconsistent with equals."
*
* @param o1 the first object to be compared.
* @param o2 the second object to be compared.
* @return a negative integer, zero, or a positive integer as the
* first argument is less than, equal to, or greater than the
* second.
* @throws NullPointerException if an argument is null and this
* comparator does not permit null arguments
* @throws ClassCastException if the arguments' types prevent them from
* being compared by this comparator.
*/
int compare(T o1, T o2);
根据compare方法的说明可知:
当第一个参数=第二个参数时,返回值是0;
当第一个参数>第二个参数时,返回值是正数;
当第一个参数<第二个参数时,返回值是负数;
2.Comparetor函数式接口的简述(本部分转载自8.函数式接口Comparator)
本部分轉載自:8.函数式接口Comparator;(PS:作者是個巨佬,他的其他文章也很具參考價值!!!)
關於default關鍵字,以前也介紹過,這是對接口的一種"寬容";具體可參考Java多态八:接口中的默认方法;接口中的静态方法;接口应用中的常见问题;文末comments:静态方法和静态属性在继承中的性质這篇文章。
(上面sort其传入的是Comparator接口的是一个实现,而没有传入Lambda表达式~~~)
(还好,这儿是根据sort()方法的特性,和Comparator中compare方法的特性,结合实际的业务需求,完成了下面的代码啦)
最后
以上就是真实服饰为你收集整理的Lambda表达式九:补充二:Stream接口的sorted()方法,Comparator函数式接口效果展示;Comparator函数式接口;函数式接口严格规范;的全部内容,希望文章能够帮你解决Lambda表达式九:补充二:Stream接口的sorted()方法,Comparator函数式接口效果展示;Comparator函数式接口;函数式接口严格规范;所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复