一:collect
- 功能:将流中的数据按照传递的方法进行收集,例如收集成List,Set,Map等等。
collect接口情况:
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);
@FunctionalInterface
public interface Supplier<T> {
T get();
}
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
//还要一个静态方法,先进行忽略
}
}
我们先看一下两个函数接口:Supplier:只有一个get方法,没有参数,返回T类型。BiConsumer:accept,接受两个参数T+U没有结果返回。
文档描述:
Performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container,such as an ArrayList, and elements are incorporated by updating the state of the result rather than by replacing the result.
大致意思:我们提供一个容器,使用提供的方法对流中的数据之于容器进行操作。好比一个ArrayList,可以将流中的数据添加进去。
方法运行效果如下:
R result = supplier.get();
for (T element : this stream){
accumulator.accept(result, element);
return result;
}
结论:
- supplier:提供一个容器。
- accumulator:提供一个累计方法,将流中数据对容器进行操作,没有返回值。
- combiner:将容器进行合并,并行操作时才有效果。
ArrayList添加数据实例:
List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6);
ArrayList<Integer> collect = num.stream().collect(() -> new ArrayList<Integer>(), (x, y) -> {
//这个判断,为了区分下
if (y % 2 == 0) x.add(y);
}, (x, y) -> {
x.addAll(y);
});
System.out.println(collect);
二:收集器方法
收集主要功能:
- 数据转化为集合
- 数据转化为数值
- 数据进行分块/分组
对部分方法进行列举:
方法名称 | 方法效果 |
---|---|
toSet | 数据收集为Set |
toList | 数据收集为List |
toMap | 收集收集为Map |
maxBy | 最大值 |
minBy | 最小值 |
groupBy | 数据根据条件分为多个Map |
partitioningBy | 根据断言分为两个Map |
joinjing | 转化为字符串,添加间隔符,前缀,后缀 |
… | … |
三:部分方法实例
- toList
List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6);
//加了一个过滤器区分一下
List<Integer> list = num.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
- toMap
person p1 = new person("大黄",15);
person p2 = new person("大黑",12);
person p3 = new person("大白",18);
List<person> list = Arrays.asList(p1, p2, p3);
Map<String, Integer> map = list.stream().collect(Collectors.toMap(person::getName, person::getAge));
- maxBy
List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6);
//maxBy里面为一个比较器,
Integer max = num.stream().collect(Collectors.maxBy((x,y)->x>y?1:-1)).get();
System.out.println(max);
- groupBy
根据我们提供的断言进行分组,格式为Map<Boolean,数据>。
List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<Boolean, List<Integer>> map = num.stream().collect(Collectors.partitioningBy(x -> x % 2 == 0));
- partitioningBy
person p1 = new person("大黄");
person p2 = new person("大黑");
person p3 = new person("大白");
List<person> list = Arrays.asList(p1, p2, p3);
Map<String, List<person>> collect1 = list.stream().collect(Collectors.groupingBy(p -> p.getName()));
- joinjing
person p1 = new person("大黄",15);
person p2 = new person("大黑",12);
person p3 = new person("大白",18);
List<person> list = Arrays.asList(p1, p2, p3);
String str = list.stream().map(person::getName).collect(Collectors.joining(","));
System.out.println(str);