lambda常用操作
程序员文章站
2022-05-07 19:01:38
package com.wlf.jdk8test;import com.wlf.entity.Person;import javax.swing.text.html.parser.Entity;import java.util.Arrays;import java.util.Comparator;import java.util.List;import java.util.stream.Collectors;/** * @author LifengWang * @create 20....
package com.wlf.jdk8test; import com.wlf.entity.Person; import javax.swing.text.html.parser.Entity; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * @author LifengWang * @create 2020-07-05 23:29 */ public class Test { public static void main(String[] args) { Person p1=new Person("zhagnsan",20); Person p2=new Person("lisi",40); Person p3=new Person("wangwu",60); Person p4=new Person("zhaoliu",25); Person p5=new Person("tianqi",30); Person p6=new Person("niuba",10); Person p7=new Person("niuba",10); //去重添加 List<Person> list= Arrays.asList(p1,p2,p3,p4,p5,p6,p7); // 获取所有名字信息 List<String> list1 = list.stream().map(Person::getName).collect(Collectors.toList()); list1.forEach(System.out::println); //排序年龄 List<Person> list2 = list.stream().sorted(Comparator.comparingInt(Person::getAge)).collect(Collectors.toList()); list2.forEach(System.out::println); // 排序操作 默认排序和倒序 List<Person> list3 = list.stream().sorted(Comparator.comparingInt(Person::getAge).reversed()).collect(Collectors.toList()); list3.forEach(System.out::println); // 过滤Filter List<Person> list4 = list.stream().filter(person -> person.getAge() > 30).collect(Collectors.toList()); list4.forEach(System.out::println); // 获取最大年龄 Integer maxAge = list.stream().map(person -> person.getAge()).max(Integer::compareTo).get(); System.out.println(maxAge); // 获取最小年龄 Integer minAge = list.stream().map(person -> person.getAge()).min(Integer::compareTo).get(); System.out.println(minAge); //获取数量 long count = list.stream().map(Person::getAge).count(); System.out.println(count); // 获取平均年龄 double asDouble = list.stream().mapToInt(Person::getAge).average().getAsDouble(); System.out.println(asDouble); //获取第一个对象 Person person = list.stream().findFirst().get(); System.out.println(person); // 将名字都转换为大写 List<String> collect = list.stream().map(Person::getName).map(String::toUpperCase).collect(Collectors.toList()); collect.forEach(System.out::println); // 忽略第一个调数据 List<Person> list7 = list.stream().sorted(Comparator.comparingInt(Person::getAge).reversed()).skip(1).collect(Collectors.toList()); list7.forEach(System.out::println); // 去重 List<Person> list8 = list.stream().distinct().collect(Collectors.toList()); list8.forEach(System.out::println); } }
本文地址:https://blog.csdn.net/wang_lifeng/article/details/107147864