一、sorted 函数
二、limit 函数
三、实战
执行结果:
一、sorted 函数
-
对流进行自然排序,其中的元素必须实现Comparable 接口
-
sorted(Comparator<? super T>comparator) 用来自定义升降序
二、limit 函数
-
获取指定数量的元素
-
(limit(long maxSize);
-
场景:成绩前几,积分排名等
三、实战
package com.learning.javalearning.lambda.chapter5;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Sorted_LimitedDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("Spring Boot", "Python", "微服务", "高并发", "Redis", "MongoDB");
List<String> resultList = list.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(">> sorted() 默认升序:");
System.out.println(resultList + "\n");
Collections.reverse(resultList);
System.out.println(">> 使用翻转Collections.reverse(list):及降序");
System.out.println(resultList + "\n");
resultList = list.stream()
.sorted(Comparator.comparing(obj -> obj.length()))
.collect(Collectors.toList());
System.out.println(">> 自定义--按照长度排序,默认升序:");
System.out.println(resultList + "\n");
resultList = list.stream()
.sorted(Comparator.comparing(String::length).reversed())
.collect(Collectors.toList());
System.out.println(">> 使用翻转reversed():及降序");
System.out.println(resultList + "\n");
resultList = list.stream()
.sorted(Comparator.comparing(String::length).reversed())
.limit(3)
.collect(Collectors.toList());
System.out.println(">> limit(3):获取前3");
System.out.println(resultList + "\n");
}
}