From aae72484f19d62c98cfb8490ccd126d7be03ce20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=87=A7=E8=87=A7?= <2556450572@qq.com> Date: Wed, 24 Aug 2022 13:16:31 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=B9EasyStream=E4=B8=AD=E8=A1=A5=E5=85=85p?= =?UTF-8?q?eekIdx()=E6=96=B9=E6=B3=95,mapMulti=E9=80=82=E9=85=8D=E4=BA=8E?= =?UTF-8?q?=E6=9B=B4=E9=AB=98=E7=89=88=E6=9C=ACJDK?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/hutool/core/stream/EasyStream.java | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/hutool-core/src/main/java/cn/hutool/core/stream/EasyStream.java b/hutool-core/src/main/java/cn/hutool/core/stream/EasyStream.java index dbc35d1e0..cd8f71d19 100644 --- a/hutool-core/src/main/java/cn/hutool/core/stream/EasyStream.java +++ b/hutool-core/src/main/java/cn/hutool/core/stream/EasyStream.java @@ -25,6 +25,7 @@ import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; @@ -526,7 +527,7 @@ public class EasyStream implements Stream, Iterable { * @param 拆分后流的元素类型 * @return 返回叠加拆分操作后的流 */ - public EasyStream mapMulti(final BiConsumer> mapper) { + public EasyStream mapMulti(final BiConsumer> mapper) { Objects.requireNonNull(mapper); return flatMap(e -> { final FastStreamBuilder buffer = EasyStream.builder(); @@ -630,6 +631,31 @@ public class EasyStream implements Stream, Iterable { return new EasyStream<>(stream.peek(action)); } + /** + * 返回与指定函数将元素作为参数执行后组成的流。操作带下标,并行流时下标永远为-1 + * 这是一个无状态中间操作 + * @param action 指定的函数 + * @return 返回叠加操作后的FastStream + * @apiNote 该方法存在的意义主要是用来调试 + * 当你需要查看经过操作管道某处的元素和下标,可以执行以下操作: + *
{@code
+	 *     .of("one", "two", "three", "four")
+	 * 				.filter(e -> e.length() > 3)
+	 * 				.peekIdx((e,i) -> System.out.println("Filtered value: " + e + " Filtered idx:" + i))
+	 * 				.map(String::toUpperCase)
+	 * 				.peekIdx((e,i) -> System.out.println("Mapped value: " + e + " Filtered idx:" + i))
+	 * 				.collect(Collectors.toList());
+	 * }
+ */ + public EasyStream peekIdx(BiConsumer action) { + Objects.requireNonNull(action); + if (isParallel()) { + return peek(e -> action.accept(e, NOT_FOUND_INDEX)); + } else { + AtomicInteger index = new AtomicInteger(NOT_FOUND_INDEX); + return peek(e -> action.accept(e, index.incrementAndGet())); + } + } /** * 返回叠加调用{@link Console#log(Object)}打印出结果的流 *