Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。Stream的遍历、匹配非常简单
ublic static void test2() {
//筛选出Integer集合中大于7的元素,并打印出来
List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2, 9);
Stream<Integer> stream = list.stream();
stream.filter(x -> x > 7).forEach(System.out::println);
//筛选员工中工资高于8000的人,并形成新的集合
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("韩梅梅", 8900,22, "女", "武汉"));
personList.add(new Person("李磊", 7000,33, "男", "上海"));
personList.add(new Person("Lucy", 7800,44, "女", "北京"));
personList.add(new Person("狗哥", 8200,55, "男", "深圳"));
personList.add(new Person("Lily", 9500,66, "女", "深圳"));
personList.add(new Person("Jim", 7900,77, "男", "深圳"));
List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
.collect(Collectors.toList());
System.out.print("高于8000的员工姓名:" + fiterList);
-
-
- 映射(map/flatMap)
-
映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap。
- map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
- flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
public static void test6(){
//3. 将员工的薪资全部增加1000
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("韩梅梅", 8900, 18,"女", "武汉"));
personList.add(new Person("李磊", 7000,19, "男", "上海"));
personList.add(new Person("Lucy", 7800,17, "女", "北京"));
personList.add(new Person("狗哥", 8200,18, "男", "深圳"));
personList.add(new Person("Lily", 9500,17, "女", "深圳"));
personList.add(new Person("Jim", 7900,17, "男", "深圳"));
// 改变原来员工集合的方式
List<Person> personListNew2 = personList.stream().map(person -> {
person.setSalary(person.getSalary() + 10000);
return person;
}).collect(Collectors.toList());
// 不改变原来员工集合的方式
List<Person> personListNew = personList.stream().map(person -> {
Person personNew = new Person(person.getName(), 0, 0, null, null);
personNew.setSalary(person.getSalary() + 10000);
return personNew;
}).collect(Collectors.toList());
//将两个字符数组合并成一个新的字符数组。
List<String> list = Arrays.asList("m-k-l-a", "1-3-5-7");
List<String> listNew = list.stream().flatMap(s -> {
// 将每个元素转换成一个stream
String[] split = s.split("-");
Stream<String> s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());
System.out.println("处理前的集合:" + list);
System.out.println("处理后的集合:" + listNew);
}