Java8 通过foreach 遍历List,同时输出下标
生活随笔
收集整理的這篇文章主要介紹了
Java8 通过foreach 遍历List,同时输出下标
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義lambada式工具類:
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());} }功能代碼演示:
value.stream().forEach(LambadaTools.forEachWithIndex((item, index)->{// 當前生成序號Integer currentSeqNo = seqNOMax + index + 1;// 設置默認盒寬度item.setBoxWidth(2.0);// 補全盒涉及庫房信息String address = this.getWarehourseByLocation(item.getSid(), list, warehourseList);if(StringUtils.isNotEmpty(address)){String[] warehourseArray = address.split("-");item.setWarehouseSid(warehourseArray[0]);item.setColumnSid(warehourseArray[1]);item.setSegmentSid(warehourseArray[2]);item.setLayerSid(warehourseArray[3]);}// 設置盒序號item.setSeqNo(currentSeqNo);// 設置批次號item.setBatchNo(StringFormatUtil.addZeroForNum(String.valueOf(batchNoMax), 5));// 生成案卷號= 項目/工程檔號+ 盒序號item.setBoxRegNo(this.getBoxRegNoByBoxSid(currentSeqNo, item.getSid()));}));總結
以上是生活随笔為你收集整理的Java8 通过foreach 遍历List,同时输出下标的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu18.04安装Nvidia显
- 下一篇: 使用Java模拟登录