首页 » 网站推广 » foreachindexphp技巧_在Java8中foreach轮回若何获取对象的index下标看完后真简单

foreachindexphp技巧_在Java8中foreach轮回若何获取对象的index下标看完后真简单

duote123 2024-11-05 0

扫一扫用手机浏览

文章目录 [+]

Consumer<String> consumer = t -> System.out.println(t);consumer.accept("single");BiConsumer<String, String> biConsumer = (k, v) -> System.out.println(k+":"+v);biConsumer.accept("multipart","double params");

输出结果:

singlemultipart:double params

这里不难创造我们平时写的箭头函数实在是一个Consumer或者BiConsumer工具

foreachindexphp技巧_在Java8中foreach轮回若何获取对象的index下标看完后真简单

定制Consumer

foreach源码

foreachindexphp技巧_在Java8中foreach轮回若何获取对象的index下标看完后真简单
(图片来自网络侵删)

default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); }}

剖析源码可知,我们的list foreach方法传入的是Consumer工具,支持一个参数,而我们想要的是item,index两个参数,很明显不知足,这时我们可以自定义一个Consumer,传参是BiConsumer,这样就能知足我们需求了,代码如下:

import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer;import java.util.function.Consumer;public class LambadaTools { / 利用BiConsumer实现foreach循环支持index @param biConsumer @param <T> @return / public static <T> Consumer<T> forEachWithIndex(BiConsumer<T, Integer> biConsumer) { /这里解释一下,我们每次传入forEach都是一个重新实例化的Consumer工具,在lambada表达式中我们无法对int进行++操作, 我们仿照AtomicInteger工具,写个getAndIncrement方法,不能直策应用AtomicInteger哦/ class IncrementInt{ int i = 0; public int getAndIncrement(){ return i++; } } IncrementInt incrementInt = new IncrementInt(); return t -> biConsumer.accept(t, incrementInt.getAndIncrement()); }}

调用示例:

List<String> list = new ArrayList();list.add("111");list.add("222");list.add("333");list.forEach(LambadaTools.forEachWithIndex((item, index) -> { System.out.println(index +":"+ item);}));

输出结果如下:

0:1111:2222:333

PS:这个Set也可以用哦,不过在Set利用中这个index可不是下标

看完这篇文章你学会了吗?

把稳一下咯:由于篇幅缘故原由,

作者:RhapsodyDandelion链接:https://juejin.cn/post/6951283538687688717来源:掘金

相关文章

大数据格言,引领智慧时代的前行灯塔

大数据时代,信息爆炸,数据成为推动社会进步的重要力量。在这个过程中,许多关于大数据的格言应运而生,为我们揭示了大数据的价值和意义。...

网站推广 2024-12-16 阅读0 评论0

大数据比值,提示时代变革的利器

随着信息技术的飞速发展,大数据时代已经来临。在这个时代,数据已经成为最宝贵的资源之一。而大数据比值,作为衡量数据价值的重要指标,正...

网站推广 2024-12-16 阅读0 评论0

大数据泡沫破灭,反思与启示

近年来,随着互联网、物联网、人工智能等技术的快速发展,大数据产业在我国蓬勃发展。在一片繁荣的背后,大数据泡沫逐渐显现。本文将分析大...

网站推广 2024-12-16 阅读0 评论0