package test;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class TestFunction {
static class Student{
String name;
Integer id;
public Student(String name, Integer id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Integer getId() {
return id;
}
}
public static void main(String[] args) {
List<Student> list= Arrays.asList(new Student("jack",1),new Student("tom",11),new Student("tom",5),new Student("tom",10));
// Integer reduce = list.stream().map((e) -> {
// return e.getId();
// }).reduce(0, (x, y) -> {
// return x + y;
// });
// System.out.println(reduce);
list.stream().sorted(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
System.out.println("o1="+o1.getId()+";o2="+o2.getId());
if(o1.getId()==1)
return 1;
if(o2.getId()==1)
return -1;
return o1.getId()-o2.getId();
}
}).forEach((student -> System.out.println(student.getId())));
}
}
- Compare的返回值反应的是两个参数的权重,返回值为1时,前者(o1)权重大,返回值为-1时,后者(o2)权重大。然后排序结果按照权重(注意这里不是值的大小)由小到大进行排序。即权重默认升序排列。
- 例:o1 =4 ,o2 = 6;
return o2 – o1; {即返回值为正数,即为1,那么前者权重大,排序为o2,o1;
即为6,4,值降序排列}
return o1 – o2; {即返回值为负数,即为-1,那么后者权重大,排序为o1,o2;
即为4,6,值升序排列}