Stream的方法描述与实例
1,filter 过滤
Person p1 = new Person(); p1.setName("P1"); p1.setAge(10); Person p2 = new Person(); p2.setName("pp2"); p2.setAge(9); Person p3 = new Person(); p3.setName("p3"); p3.setAge(5); List<Person> list = new ArrayList<>(); list.add(p1); list.add(p2);
//若最后不添加collect方法,则返回类型是stream list = list.stream().filter(person -> person.getAge()>5).collect(Collectors.toList()); System.out.println(list); 输出结果: [Person{name=‘P1‘, age=10}, Person{name=‘pp2‘, age=9}]
2,map
List<String> list = Stream.of("a","b","wo").map(string -> string.toUpperCase()).collect(Collectors.toList());
System.out.print(list);
输出结果:
[A, B, WO]
3,mapToInt
List<Integer> list = Stream.of("1","2").mapToInt(e ->Integer.parseInt(e)).boxed().collect(Collectors.toList()); //maptoInt之后是IntStream类型,需要用boxed转换为Stream