Java8中用foreach循环获取对象的index下标详解

2025-05-29 0 71

前言

在Java8中,我们经常使用lambada表达式进行foreach循环,但是常常我们在遍历List的时候想获取对象的index,但是Java8、9、10、11都没有相关的支持,同样的问题也存在于增强型for循环中,很多时候不得不含着泪以 for (int i = 0; i < list.size(); i++) 的方式写代码

我们的期望

?

1
list.foreach((item,index)->{}) //编译不通过

常见的list获取index方法

for(int i=0;i<list.size();i++>)

?

1

2
for (int i = 0; i < list.size(); i++) {

}

indexOf(Obj)

?

1

2

3
for (Object o : list) {

list.indexOf(o); //如果是Set还没有这个方法

}

还有…

?

1

2

3

4
int i = 0;

for (String s : list) {

i++;

}

很显然上述的方法并不是我们所想要的

Consumer和BiConsumer

我们看个简单的例子

?

1

2

3

4
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");

输出结果:

single
multipart:double params

这里不难发现我们平时写的箭头函数其实是一个Consumer或者BiConsumer对象

定制Consumer

foreach源码

?

1

2

3

4

5

6
default void forEach(Consumer<? super T> action) {

Objects.requireNonNull(action);

for (T t : this) {

action.accept(t);

}

}

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26
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());

}

}

调用示例:

?

1

2

3

4

5

6

7
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:111
1:222
2:333

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

总结

到此这篇关于Java8中用foreach循环获取对象的index下标的文章就介绍到这了,更多相关Java8获取对象index下标内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://juejin.cn/post/6951283538687688717

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java8中用foreach循环获取对象的index下标详解 https://www.kuaiidc.com/107604.html

相关文章

发表评论
暂无评论