带你读《2022技术人的百宝黑皮书》——如何避免写重复代码:善用抽象和组合(2)https://developer.aliyun.com/article/1339968?groupCode=taobaotech
实现 bufferUntilChanged
Source.from(Arrays.asList("A", "B", "B", "C", "C", "C", "D")) .statefulMap( () -> (List<String>) new LinkedList<String>(), (buffer, element) -> { if (buffer.size() > 0 && (!buffer.get(0).equals(element))) { return Pair.create( new LinkedList<>(Collections.singletonList(element)), Collections.unmodifiableList(buffer)); } else { buffer.add(element); return Pair.create(buffer, Collections.<String>emptyList()); } }, Optional::ofNullable) .filterNot(List::isEmpty) .runForeach(System.out::println, system); // prints // [A] // [B, B] // [C, C, C] // [D]
举一反三,如何实现 distinctUntilChanged呢 ?
实现 distinctUntilChanged
Source.from(Arrays.asList("A", "B", "B", "C", "C", "C", "D")) .statefulMap( Optional::<String>empty, (lastElement, element) -> { if (lastElement.isPresent() && lastElement.get().equals(element)) { return Pair.create(lastElement, Optional.<String>empty()); } else { return Pair.create(Optional.of(element), Optional.of(element)); } }, listOnComplete -> Optional.empty()) .via(Flow.flattenOptional()) .runForeach(System.out::println, system); // prints // A // B // C // D
如果要实现聚合buffer呢?
带你读《2022技术人的百宝黑皮书》——如何避免写重复代码:善用抽象和组合(4)https://developer.aliyun.com/article/1339966?groupCode=taobaotech