Ani*_*h N 6 java java-8 java-stream
例如#1
[1, 1, 1, 2, 22, 35, 35, 120, 320]==>>[3, 2, 22, 70, 120, 320]
请注意如何将重复的连续 1 和 35 分别合并为 3 和 70
例如#2
[1,1,3,1,1]==>>[2,3,2]
Stream.of(1, 1, 1, 2, 22, 35, 35, 120, 320)
.collect(Collectors.toMap(
Function.identity(),
Function.identity(),
Integer::sum,
LinkedHashMap::new
))
.values()
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
如果您发表评论,您将需要一个自定义收集器,实际上:
static class Custom implements Collector<Integer, List<Integer>, List<Integer>> {
private Integer match;
@Override
public Supplier<List<Integer>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<Integer>, Integer> accumulator() {
return (list, x) -> {
int lastIndex = list.size() - 1;
if (match != null && match.equals(x)) {
list.set(lastIndex, list.get(lastIndex) + x);
} else {
match = x;
list.add(x);
}
};
}
@Override
public BinaryOperator<List<Integer>> combiner() {
return (left, right) -> {
throw new RuntimeException("Not for parallel");
};
}
@Override
public Function<List<Integer>, List<Integer>> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return Set.of();
}
}
Run Code Online (Sandbox Code Playgroud)
用法是:
public static void main(String[] args) {
Stream.of(1, 1, 3, 1, 1)
.collect(new Custom())
.forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
202 次 |
| 最近记录: |