2016-06-08 86 views
0

內實例我該怎麼辦了Java 8個流做Java的8個流

for (List<Category> parentPath : getPathsInternal(parent, controlSet)) { 
    if (!(parentPath instanceof LinkedList)) { 
    parentPath = new LinkedList<Category>(parentPath); 
    } 
    parentPath.add(category); 
    result.add(parentPath); 
} 

內實例,我不知道如何用Java編寫8個流等功能。任何方向?

if (!(parentPath instanceof LinkedList)) { 
    parentPath = new LinkedList<Category>(parentPath); 
    } 
+2

你知道lambda可以是多行,對不對?他們可以包括你想要的任何陳述? –

+0

我可以做getPath ... Stream()。forEach(....所有邏輯..)但我想看到更好的方式,這可能是可能的 –

+2

在99%的所有'LinkedList'用法中,它是錯誤的選擇。另外1%無論如何都需要重新設計一個完整的應用程序。那麼,爲什麼你要將非'LinkedList'轉換爲'LinkedList's,爲什麼你要做*有條件的*?是否「有時修改源代碼」真的是你想實現的目標? – Holger

回答

3
getPathsInternal(parent, controlSet).stream() 
    .map(parentPath -> 
     (parentPath instanceof LinkedList) 
      ? parentPath : new LinkedList<>(parentPath)) 
    .peek(parentPath -> parentPath.add(category)) 
    .collect(toList()); // or whatever result is 
+0

我認爲使用'peek()'產生副作用通常是不被接受的。雖然OP的問題比你的回答更具問題。 – shmosel

+1

'peek'的整個_point_是副作用。它從字面上不能用於其他任何事情。 (但是,試圖做副作用是有問題的。) –

+0

我的意思是除了用於調試目的。有一個原因被稱爲「偷看」,而不是「做」或「消耗」。 – shmosel

2

我覺得這個代碼是相同的:

getPathsInternal(parent, controlSet).stream() 
    .map(parentPath -> (parentPath instanceof LinkedList) ? parentPath : new LinkedList<>(parentPath)) 
    .peek(parentPath -> parentPath.add(category)) 
    .collect(Collectors.toList()) 
1

還有一堆的方法可以做到這一點,但可能是最可讀的是分裂成兩個功能成語。

List<Category> result = getPathsInternal(parent, controlSet).stream() 
    .map((parentPath) -> parentPath instanceof LinkedList ? parentPath : new LinkedList<>()) 
    .collect(Collectors.toList()) 
result.stream() 
    .forEach((parentPath) -> parentPath.add(category)); 
+0

如果你不打算在結果中使用流函數,你也可以使用List :: forEach來代替:result.forEach(parentPath - > parentPath.add(category)); – srborlongan

0

添加到約偷看從路易斯的回答發起討論:

由於

parentPath.add(category) 

是相當的流對象本身的轉變,我認爲這是一個地圖操作,即使你在這種情況下必須使用塊語法:

getPathsInternal(parent, controlSet).stream() 
    .map(parentPath -> 
     (parentPath instanceof LinkedList) 
      ? parentPath : new LinkedList<>(parentPath)) 
    .map(parentPath -> { parentPath.add(category); return parentPath; }) 
    .collect(toList());