前面几节我们看了一下基础的函数式编程的接口,这一节我们看一下Stream流,它重新定义了集合的使用方式。
- 过滤某些元素
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//打印小于7的元素
List<Integer> result = list.stream().filter(integer -> integer<7).collect(Collectors.toList());
result.forEach(System.out::println);
- 求集合的最大值、最小值、平均值和综合
int[] intArr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
IntStream intStream = Arrays.stream(intArr);
int sum = intStream.sum();
intStream = Arrays.stream(intArr);
int max = intStream.max().getAsInt();
intStream = Arrays.stream(intArr);
int min = intStream.min().getAsInt();
intStream = Arrays.stream(intArr);
double avg = intStream.average().getAsDouble();
- 数组转Map
Integer[] intArr = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List list = Arrays.asList(intArr);
Map<String,Integer> o1 = (Map<String,Integer>) list.stream().collect(Collectors.toMap(o -> o+"", o -> o));
- 对象列表转Map
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test4 {
public static void main(String[] args) {
User user = new User("ali","java");
User user1 = new User("xiaoli","java");
User user2= new User("ali1","python");
User user3 = new User("xiaoli1","python");
User user4 = new User("zhangli","python");
List<User> list = new ArrayList<>();
list.add(user);
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
// list转map
Map<String, String> map = list.stream().collect(Collectors.toMap(User::getName, User::getClassName));
// 统计每个班有多少人
Map<String, List<User>> groupBy = list.stream().collect(Collectors.groupingBy(User::getClassName));
}
}
class User{
String name;
String className;
public User(String name, String className) {
this.name = name;
this.className = className;
}
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
- 判断包含与否
List<String> strs = Arrays.asList("1", "2", "1", "3", "4");
boolean aa = strs.stream().anyMatch(str -> str.equals("1"));
boolean bb = strs.stream().allMatch(str -> str.equals("1"));
boolean cc = strs.stream().noneMatch(str -> str.equals("1"));
long count = strs.stream().filter(str -> str.equals("1")).count();
流编程的应用远不止这么几个,根据需求不同还有好多变化,这里只提供了一些常见的demo。