Java Functional Programming: How to convert a if-else ladder inside for loop to functional style?

Gop*_*ala 5 java functional-programming declarative-programming java-8 vavr

The expectation is derive 3 lists itemIsBoth, aItems, bItems from the input list items. How to convert code like below to functional style? (I understand this code is clear enough in an imperative style, but I want to know does declarative style really fail to deal with such a simple example). Thanks.

for (Item item: items) {
    if (item.isA() && item.isB()) {
        itemIsBoth.add(item);
    } else if (item.isA()) {
        aItems.add(item);
    } else if (item.isB()){
        bItems.add(item)
    }
}
Run Code Online (Sandbox Code Playgroud)

SDJ*_*SDJ 7

问题标题非常广泛(转换if-else阶梯),但是由于实际问题询问的是特定情况,因此让我提供一个样本,至少可以说明可以做什么。

因为该if-else结构基于应用于该项目的谓词创建了三个不同的列表,所以我们可以将这种行为声明为一个分组操作。开箱即用的功能唯一需要做的就是使用标签对象折叠多个布尔谓词。例如:

class Item {
    enum Category {A, B, AB}

    public Category getCategory() {
        return /* ... */;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,逻辑可以简单表示为:

Map<Item.Category, List<Item>> categorized = 
    items.stream().collect(Collectors.groupingBy(Item::getCategory));
Run Code Online (Sandbox Code Playgroud)

在给定类别的情况下,可以从地图中检索每个列表。

如果无法更改类Item,则可以通过移动枚举声明和分类方法超出类的大小来实现相同的效果Item(该方法将成为静态方法)。