Java8中用foreach循環(huán)獲取對象的index下標詳解
前言
在Java8中,我們經(jīng)常使用lambada表達式進行foreach循環(huán),但是常常我們在遍歷List的時候想獲取對象的index,但是Java8、9、10、11都沒有相關的支持,同樣的問題也存在于增強型for循環(huán)中,很多時候不得不含著淚以 for (int i = 0; i < list.size(); i++) 的方式寫代碼
我們的期望
list.foreach((item,index)->{}) //編譯不通過
常見的list獲取index方法
for(int i=0;i<list.size();i++>)
for (int i = 0; i < list.size(); i++) { }
indexOf(Obj)
for (Object o : list) { list.indexOf(o); //如果是Set還沒有這個方法 }
還有…
int i = 0; for (String s : list) { i++; }
很顯然上述的方法并不是我們所想要的
Consumer和BiConsumer
我們看個簡單的例子
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");
輸出結(jié)果:
single
multipart:double params
這里不難發(fā)現(xiàn)我們平時寫的箭頭函數(shù)其實是一個Consumer或者BiConsumer對象
定制Consumer
foreach源碼
default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }
分析源碼可知,我們的list foreach方法傳入的是Consumer對象,支持一個參數(shù),而我們想要的是item,index兩個參數(shù),很明顯不滿足,這時我們可以自定義一個Consumer,傳參是BiConsumer,這樣就能滿足我們需求了,代碼如下:
import java.util.ArrayList; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; public class LambadaTools { /** * 利用BiConsumer實現(xiàn)foreach循環(huán)支持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()); } }
調(diào)用示例:
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); }));
輸出結(jié)果如下:
0:111
1:222
2:333
PS:這個Set也可以用哦,不過在Set使用中這個index可不是下標
總結(jié)
到此這篇關于Java8中用foreach循環(huán)獲取對象的index下標的文章就介紹到這了,更多相關Java8獲取對象index下標內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot登錄、退出、獲取用戶信息的session處理方案
這篇文章主要介紹了SpringBoot登錄、退出、獲取用戶信息的session處理,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08@PreAuthorize、@PostAuthorize、@PreFilter、@PostFilter注解的用法詳解
這篇文章主要介紹了@PreAuthorize、@PostAuthorize、@PreFilter、@PostFilter注解的用法詳解,通過在方法上添加@PreAuthorize注解,可以指定需要滿足的權限條件,只有滿足條件的用戶才能執(zhí)行該方法,需要的朋友可以參考下2023-10-10Springboot使用異步請求提高系統(tǒng)的吞吐量詳解
這篇文章主要介紹了Springboot使用異步請求提高系統(tǒng)的吞吐量詳解,和同步請求相對,異步不需要等待響應,隨時可以發(fā)送下一次請求,如果是同步請求,需要將信息填寫完整,再發(fā)送請求,服務器響應填寫是否正確,再做修改,需要的朋友可以參考下2023-08-08