lambda表达式的一些学习
关于lambda表达式的一些学习,例举出来。
1.学生实体类
public class Student { private String name; private int age; public String getName() { return name; } public Student setName(String name) { this.name = name; return this; } public int getAge() { return age; } public Student setAge(int age) { this.age = age; return this; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
2.操作对象有关的方法
public class Test { public static void main(String[] args) { List<Student> list = new ArrayList<>(); for (int i = 0; i < 4; i++) { list.add(new Student().setAge(i + 10).setName("yiqq" + i)); } //直接返回对象 Student student = list.stream().filter(a -> "yiqq0".equals(a.getName())).findFirst().orElse(null); System.out.println(student); //返回Optional Optional<Student> firstA = list.stream().filter(a -> "yiqq0".equals(a.getName())).findFirst(); Student stu = firstA.orElse(null); System.out.println(stu); //获取对象 if (firstA.isPresent()) { Student stus = firstA.get(); System.out.println(stus); } //返回集合 List<Student> studentList = list.stream().filter(a -> "yiqq0".equals(a.getName())).collect(Collectors.toList()); System.out.println(studentList); //取对象中所有的id的集合 List<Integer> integerList = list.stream().map(Student::getAge).distinct().collect(Collectors.toList());//distinct去重 System.out.println(integerList); } }
3.lambda表达式的一些用法
public class TestL { public static void main(String[] args) { String[] atp = {"00006", "00002","00001","00005","00004", "00003"}; Arrays.sort(atp, new Comparator<String>() { @Override public int compare(String s1, String s2) { return (s1.compareTo(s2)); } }); Arrays.sort(atp, (String s1, String s2) -> (s1.compareTo(s2)));//Lambdas排序集合 List<String> players = Arrays.asList(atp);//数组转list集合 String [] array = players.toArray(new String[0]);//list集合转数组 System.out.println(Arrays.toString(array));//数组转化为string输出 // 以前的循环方式 for (String player : players) { System.out.print(player + "; "); } // 使用 lambda 表达式以及函数操作(functional operation) players.forEach((player) -> System.out.print(player + "; ")); // 在 Java 8 中使用双冒号操作符(double colon operator) players.forEach(System.out::println); } }
程序员的眼里,不止有代码和bug,还有诗与远方和妹子!!!