public static void main(String[] args) { List<Student> stuList = new ArrayList<Student>(); Student st1 = new Student("123","aaa"); Student st2 = new Student("234","bbb"); Student st3 = new Student("345","ccc"); Student st4 = new Student("345","ccc"); stuList.add(st1); stuList.add(st2); stuList.add(st3); stuList.add(st4); //1.提取出list对象中的一个属性 List<String> stIdList1 = stuList.stream() .map(Student::getId) .collect(Collectors.toList()); stIdList1.forEach(s -> System.out.print(s+" ")); System.out.println(); System.out.println("----------"); //2.提取出list对象中的一个属性并去重 List<String> stIdList2 = stuList.stream() .map(Student::getId).distinct() .collect(Collectors.toList()); stIdList2.forEach(s -> System.out.print(s+" ")); /* 结果: 123 234 345 345 ---------- 123 234 345 */ }
咱们知道,在java8出lambda表达式以前,是不支持在循环中直接对list进行删除的。可是java8的新特性lambda表达式,帮咱们实现了这个功能:java
List<String> lists = new ArrayList<>(); lists.add("a"); lists.add("b"); lists.add("c"); //使用removeIf方法,->里的是判断条件,若是符合这个条件就删除。这里会删除带有c的元素 lists.removeIf(s -> s.contains("c"));
java8新特性大大的简化了咱们的代码,使用更加的方便。测试
Student student = studentList.stream().max(Comparator.comparing(Student::getClassCount)).get();
java8以前是这样计算代码运行时间的code
long startTime=System.currentTimeMillis(); //获取开始时间 doSomeThing(); //测试的代码段 long endTime=System.currentTimeMillis(); //获取结束时间 System.out.println("程序运行时间: "+(end-start)+"ms");
java8以后可使用Instant获取时间戳来计算代码运行时间对象
public static void main(String[] args) { Instant start = Instant.now(); LongStream.rangeClosed( 0,110 ) //并行流 .parallel() .reduce( 0,Long::sum ); LongStream.rangeClosed( 0,110 ) //顺序流 .sequential() .reduce( 0,Long::sum ); Instant end = Instant.now(); System.out.println("耗费时间"+ Duration.between( start,end ).toMillis()); }
我的公众号《骇客与画家》,欢迎关注rem