/**
* 流排序
*/
@Test
public void test3(){
List<String> list = Arrays.asList("q", "d", "r", "s");
list.stream()
.sorted() //默认升序
.forEach(System.out::println);
}
@Test
public void test4(){
List<Book> books = Arrays.asList(
new Book("1", "a", "1", "1", 1, new Date()),
new Book("2", "b", "2", "2", 2, new Date()),
new Book("3", "c", "3", "3", 1, new Date()),
new Book("4", "d", "4", "4", 4, new Date())
);
books.stream()
.sorted((x,y) -> y.getAge() - x.getAge()) //小 - 大 升序 | 大 - 小 降序
.forEach(System.out::println);
}
//如果某字段相同 自定义排序 不同 按原先定义的排序
@Test
public void test5(){
List<Book> books = Arrays.asList(
new Book("1", "a", "1", "1", 1, new Date()),
new Book("2", "b", "2", "2", 2, new Date()),
new Book("3", "c", "3", "3", 1, new Date()),
new Book("4", "d", "4", "4", 4, new Date())
);
books.stream()
.sorted((x,y) ->{
return x.getAge() - y.getAge() == 0 ? x.getName().compareTo(y.getName()) : x.getAge().compareTo(y.getAge());
}).forEach(System.out::println);
}
// 数字的操作——通过流 获取 count max min
@Test
public void test6(){
List<Book> books = Arrays.asList(
new Book("1", "a", "1", "1", 1, new Date()),
new Book("2", "b", "2", "2", 2, new Date()),
new Book("3", "c", "3", "3", 1, new Date()),
new Book("4", "d", "4", "4", 4, new Date())
);
long count = books.stream().count();
System.out.println("个数" + count);
Optional<Book> max = books.stream().max((x, y) -> Integer.compare(x.getAge(), y.getAge()));
System.out.println("最大"+max.get().getAge());
Optional<Book> min = books.stream().min((x, y) -> Integer.compare(x.getAge(), y.getAge()));
System.out.println("最小"+min.get().getAge());
}
// 直接对数字进行比较
@Test
public void test7(){
List<Integer> integers = Arrays.asList(1, 3, 4, 5, 12, 2, 42, 13, 0);
long count = integers.stream().count();
System.out.println("个数" + count);
Optional<Integer> max = integers.stream().max((x, y) -> Integer.compare(x, y));
System.out.println("最大"+max);
Optional<Integer> min = integers.stream().min((x, y) -> Integer.compare(x, y));
System.out.println("最小"+min);
}
//另一种方式比较
// 直接对数字进行比较
//对于对象中的数字类型的属性也可以使用 Integer::compare 方法
@Test
public void test8(){
List<Integer> integers = Arrays.asList(1, 3, 4, 5, 12, 2, 42, 13, 0);
Optional<Integer> min = integers.stream().min(Integer::compare);
System.out.println("最小"+min);
Optional<Integer> max = integers.stream().max(Integer::compare);
System.out.println("最大"+max);
}
未完待续 。。。。