轉(zhuǎn)載(https://www.cnblogs.com/c9999/p/10844654.html)
public class Java8Test {
public static void main(String[] args) {
Person p1 = new Person("麻子", 31);
Person p2 = new Person("李四", 20);
Person p3 = new Person("王五", 26);
List<Person> personList = new ArrayList<Person>();
personList.add(p1);
personList.add(p2);
personList.add(p3);
//java8遍歷
personList.forEach(p -> System.out.println(p.getAge()));
//按照person的 age進(jìn)行排序
//方法一
personList.sort((o1, o2) -> o1.getAge().compareTo(o2.getAge())); //正序
personList.sort((o1, o2) -> o2.getAge().compareTo(o1.getAge())); //倒序
//方法二
personList.sort(Comparator.comparing(Person::getAge)); // 正序
personList.sort(Comparator.comparing(Person::getAge).reversed()); // 倒序
//遍歷
personList.forEach(p -> System.out.println(p.getAge()));
System.out.println("========================================");
//獲取年齡最大的Person
Person maxAgePerson = personList.stream().max(Comparator.comparing(Person::getAge)).get();
System.out.println(maxAgePerson.getAge());
System.out.println("========================================");
//獲取年齡最小的Person
Person minAgePerson = personList.stream().min(Comparator.comparing(Person::getAge)).get();
System.out.println(minAgePerson.getAge());
//過(guò)濾出年齡是20的person预鬓,想過(guò)濾出什么條件的都可以
List<Person> personList1 = personList.stream().filter(person -> person.getAge() == 20).collect(Collectors.toList());
//統(tǒng)計(jì)出年齡等于20的個(gè)數(shù)
long count = personList.stream().filter(person -> person.getAge() == 20).count();
//獲得年齡的平均值
double asDouble = personList.stream().mapToInt(person -> person.getAge()).average().getAsDouble();
//獲得年齡的求和
int sum = personList.stream().mapToInt(person -> person.getAge()).sum();
}
}