2016-04-26 7 views
0

ストリームとフィルタを使用して以下をどのように表現できますか。ありがとう。フィルタを使用するストリーム内の複数のifs

for (UIDisplayItem uiDisplayItem : uiDisplayItems) { 
    if ("8929".equals(uiDisplayItem.getProductSpecCharacteristicID())) { 
     type1 = uiDisplayItem.getValue(); 
    } 
    if ("5121".equals(uiDisplayItem.getProductSpecCharacteristicID())) { 
     type2 = uiDisplayItem.getValue(); 
    } 
    if ("4981".equals(uiDisplayItem.getProductSpecCharacteristicID())) { 
     type3 = uiDisplayItem.getValue(); 
    } 
    if ("501".equals(uiDisplayItem.getProductSpecCharacteristicID())) { 
     type4 = uiDisplayItem.getValue(); 
    } 
} 
+1

あなたにはありません。これは確実にはるかに大きなコードの一部です。ストリームとフィルタは、コードの行を美しくする魔法の杖ではありません。ここで何をしたいのかを正確に伝える必要があります。 – Tunaki

+0

確かにあなたのようなコードの塊ではありません:私はすでに4つの副作用を数えることができます。 – Tunaki

+0

代わりに 'switch'文を使うことができます。このような比較の必要性を排除するための完全な再設計はずっと推奨されています。 – Holger

答えて

0

あなたが "forEachの" と "のための" 置き換えると以下のような何かを行うことができます:

list.forEach(item -> 
     { 
      if ("8929".equals(item.getProductSpecCharacteristicID())) { 
       type1 = item.getValue(); 
      } 
      if ("5121".equals(item.getProductSpecCharacteristicID())) { 
       type2 = item.getValue(); 
      } 
      if ("4981".equals(item.getProductSpecCharacteristicID())) { 
       type3 = item.getValue(); 
      } 
      if ("501".equals(item.getProductSpecCharacteristicID())) { 
       type4 = item.getValue(); 
      } 
     }); 
関連する問題