使用过滤器的流中的多个ifs

时间:2016-04-26 13:46:44

标签: java if-statement java-8 java-stream

我们如何使用流和过滤器表示以下内容。感谢。

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 个答案:

答案 0 :(得分:0)

您可以将“for”替换为“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();
            }
        });