网站一键备份,作文网站高中,程序员怎么做自己的网站,手机页面设计软件Stream sorted() Stream sorted(Comparator? super T comparator) 对流中元素进行排序#xff0c;排序后的元素放到新流中返回。 无参的方法按照自然顺序排序#xff0c;有参数的方法根据自定义的比较器进行比较排序。 这两个方法都是有状态的中间操作#xff0c… Stream sorted() Stream sorted(Comparator? super T comparator) 对流中元素进行排序排序后的元素放到新流中返回。 无参的方法按照自然顺序排序有参数的方法根据自定义的比较器进行比较排序。 这两个方法都是有状态的中间操作对于有序流排序结果是固定的对于无序流则无法保证得到固定的排序结果。
看例子
void stream_sorted() {ListString list List.of(43,55,23,25,65);list.stream().sorted().forEach(a - System.out.print(a ));System.out.println();list.parallelStream().sorted().forEach(a - System.out.print(a ));System.out.println(\n --- --- ---);list.stream().sorted((a,b) - Integer.parseInt(b)-Integer.parseInt(a)).forEach(a - System.out.print(a ));System.out.println();list.parallelStream().sorted((a,b) - Integer.parseInt(b)-Integer.parseInt(a)).forEach(a - System.out.print(a ));}运行结果
23 25 43 55 6543 23 55 25 65--- --- ---65 55 43 25 2343 25 65 55 23list.stream().sorted().forEach(a - System.out.print(a ));这行代码是按自然顺序排序
list.stream().sorted((a,b) - Integer.parseInt(b)-Integer.parseInt(a)).forEach(a - System.out.print(a ));这行代码是根据自定义的比较器进行排序这里定义的作用就是逆序排序。
然后就是两个并行流的排序因为是并行流因此无法得到固定的顺序因此在并行流中使用这两个方法一定要慎重。 Stream实现分组后排序操作可以先排序然后再Collectors.groupingBy()分组 Stream支持并非操作不存在Stream并发时上边的方法可以实现分组后排序操作存在Stream并发时就不行会乱。