Collector接口
java.util.stream.Collector
存在4个方法,分别是
- Supplier supplier(); 创建并返回一个结果(容器/集合)
- BiConsumer accumulator(); 计算数据到上边创建到容器/集合中
- BinaryOperator combiner(); 合并2个容器.
- Function finisher(); 返回最终数据.
举例实现1
- toList ``` 1、创建集合 ArrayList::new 2、数据添加到容中(技术数据到容器中) List::add 3、合并2个数据到一个并返回 (left, right) -> { left.addAll(right); return left;} 4、返回最终数据 i -> (R) i
结合起来就是
public static >) ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}
<a name="LUU1z"></a>
#### 举例实现2
```java
//---生成数据
final List<Project> collect = IntStream.range(0, 10)
.mapToObj(x -> new Project(x, "projectName" + x))
.collect(Collectors.toList());
//---操作
final List<String> categorys = Arrays.asList("projectName1", "projectName2");
//--针对项目名字进行分组
final Map<String, List<Project>> map = collect.
stream()
.filter(x -> StringUtils.isNotBlank(x.getProjectName()))
.filter(x -> categorys.contains(x.getProjectName()))
.collect(Collectors.groupingBy(Project::getProjectName));
//-- 分组后进行转换
final List<Project> collect1 = categorys.stream()
.filter(map::containsKey)
.flatMap(x -> map.getOrDefault(x, new ArrayList<>()).stream())
.collect(new Ff());
System.out.println(JSONObject.toJSONString(collect1));
//--
class Ff implements Collector<Project, Set<String>, List<Project>> {
private final List<Project> projects = new ArrayList<>();
@Override
public Supplier<Set<String>> supplier() {
return HashSet::new;
}
@Override
public BiConsumer<Set<String>, Project> accumulator() {
return (x, i) -> {
if (x.add(i.getProjectName())) {
projects.add(i);
}
};
}
@Override
public BinaryOperator<Set<String>> combiner() {
return (integers, integers2) -> {
integers.addAll(integers2);
return integers;
};
}
@Override
public Function<Set<String>, List<Project>> finisher() {
return strings -> projects;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(Characteristics.CONCURRENT));
}
}