1、使用map()映射数据
使用map()
一般用来类型转换或者对象映射处理操作,例如,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static class Person {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
List<Person> pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
pList.stream().forEach(o->{
System.out.println("stream() map() before :"+o.getAge());
});
//截取前n个元素
List<Person> list1 = pList.stream()
.map(o -> {
o.setAge(18);
return o;
}).collect(Collectors.toList());
list1.stream().forEach(o->{
System.out.println("stream() map() :"+o.getAge());
});
System.exit(0); //success
}
}
2、使用flatMap()处理数据
map
和flatMap
都可以应用于Stream
,并且它们都返回Stream
。区别在于map操作为每个输入值生成一个输出值,而flatMap
操作为每个输入值生成任意数量的值,如下,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String[] strings = {"cjavapy", "https://www.cjavapy.com"};
List stringList = Arrays.asList(strings).stream().
map(str -> str.split("")).
flatMap(str -> Arrays.stream(str))
.collect(Collectors.toList());
stringList.stream().forEach(o->{
System.out.println("stream() flatMap():"+o);
});
System.exit(0); //success
}
}
3、使用reduce()处理数据
Stream.reduce()
则是Stream
的一个聚合方法,可以把一个Stream
的所有元素按照聚合函数成一个结果。如sum、min、max等,示例代码如下,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static class Person {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
List<Person> pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
pList.stream().forEach(o->{
System.out.println("stream() map() before :"+o.getAge());
});
//下面代码reduce()中0代表累加的初始值
//对年龄求和
Integer sum = pList.stream()
.map(Person::getAge)
.reduce(0, Integer::sum);
//求年龄最大值
Integer max = pList.stream()
.map(Person::getAge)
.reduce(0, Integer::max);
//求年龄最小值
Integer min = pList.stream()
.map(Person::getAge)
.reduce(Integer::min).orElse(0);
System.out.println(String.format("stream() sum = %s, max = %s, min = %s", sum , max , min));
System.exit(0); //success
}
}