我們正在使用 java8 中的 Streams 迭代 LinkedList,并創建另一個列表。但是由于競爭條件,結果列表大小發生了變化。List<DesInfo> InfoList = new LinkedList<>();documentList.stream()
.parallel()
.forEach(document -> {
Info descriptiveInfo = objectFactory.createDescriptiveInfo();
List<Document> documents = new ArrayList<>();
documents.add(document);
descriptiveInfo.setHotelInfo(getHotelInfo(document.get(CODE), documents));
InfoList.add(Info);
});如果我們每次看到為相同的 documentList 輸入生成不同大小的 InfoList 時都會運行此代碼。我瀏覽了一些論壇,他們提到 LinkedList 不是線程安全的,而是使用任何線程安全的集合。但我的要求不允許我改變 LinkedList。我需要使用具有相同 LinkedList 的并行流功能。
2 回答

哈士奇WWW
TA貢獻1799條經驗 獲得超6個贊
而不是使用forEach
use aCollector
和 amap()
操作:
List<HotelDescriptiveInfo> hotelDescriptiveInfoList = documentList.parallelStream() .map(document -> { HotelDescriptiveInfo descriptiveInfo = objectFactory.createHotelDescriptiveInfo(); List<Document> documents = new ArrayList<>(); documents.add(document); descriptiveInfo.setHotelInfo(getHotelInfo(document.get(HOTEL_CODE), documents)); return descriptiveInfo; }) .collect(Collectors.toCollection(LinkedList::new));
該Stream
api 將負責處理并且不允許競爭條件。

撒科打諢
TA貢獻1934條經驗 獲得超2個贊
使用collect
而不是更改集合的狀態。
首先創建一個映射函數:
private DesInfo documentToDesInfo(Document document){ DesInfo info = objectFactory.createDescriptiveInfo(); List<Document> documents = new ArrayList<>(); documents.add(document); info.setHotelInfo(getHotelInfo(document.get(CODE), documents)); return info;}
然后在您的管道中使用它:
List<DesInfo> infoList = documentList.parallelStream() .map(this::documentToDesInfo) .collect(toCollection(LinkedList::new));
添加回答
舉報
0/150
提交
取消