Java8中用foreach循環(huán)獲取對象的index下標(biāo)詳解
在Java8中,我們經(jīng)常使用lambada表達(dá)式進(jìn)行foreach循環(huán),但是常常我們在遍歷List的時(shí)候想獲取對象的index,但是Java8、9、10、11都沒有相關(guān)的支持,同樣的問題也存在于增強(qiáng)型for循環(huán)中,很多時(shí)候不得不含著淚以 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還沒有這個(gè)方法}
還有…
int i = 0;for (String s : list) { i++;}
很顯然上述的方法并不是我們所想要的
Consumer和BiConsumer我們看個(gè)簡單的例子
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é)果:
singlemultipart:double params
這里不難發(fā)現(xiàn)我們平時(shí)寫的箭頭函數(shù)其實(shí)是一個(gè)Consumer或者BiConsumer對象
定制Consumerforeach源碼
default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) {action.accept(t); }}
分析源碼可知,我們的list foreach方法傳入的是Consumer對象,支持一個(gè)參數(shù),而我們想要的是item,index兩個(gè)參數(shù),很明顯不滿足,這時(shí)我們可以自定義一個(gè)Consumer,傳參是BiConsumer,這樣就能滿足我們需求了,代碼如下:
import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer;import java.util.function.Consumer;public class LambadaTools { /** * 利用BiConsumer實(shí)現(xiàn)foreach循環(huán)支持index * * @param biConsumer * @param <T> * @return */ public static <T> Consumer<T> forEachWithIndex(BiConsumer<T, Integer> biConsumer) {/*這里說明一下,我們每次傳入forEach都是一個(gè)重新實(shí)例化的Consumer對象,在lambada表達(dá)式中我們無法對int進(jìn)行++操作,我們模擬AtomicInteger對象,寫個(gè)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:1111:2222:333
PS:這個(gè)Set也可以用哦,不過在Set使用中這個(gè)index可不是下標(biāo)
總結(jié)到此這篇關(guān)于Java8中用foreach循環(huán)獲取對象的index下標(biāo)的文章就介紹到這了,更多相關(guān)Java8獲取對象index下標(biāo)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Laravel操作session和cookie的教程詳解2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. XML入門的常見問題(一)4. css進(jìn)階學(xué)習(xí) 選擇符5. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法6. PHP字符串前后字符或空格刪除方法介紹7. jsp實(shí)現(xiàn)登錄界面8. 解析原生JS getComputedStyle9. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達(dá)式10. Echarts通過dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖
