'Java Group Objects in Custom Manner

I have a list of objects that are returned from an external API and each object looks like this:

public class Item {
    public String id;
    public int processingType;
    public String appliedToItemId;
    public Float chargeAmount;
}

Objects with a processingType value of 1 need to be "applied" to another object which will have a processingType of 0. The objects are linked with appliedToItemId and id. Once the objects are grouped then I would like to be able to merge them into one object.

This is something I could do with LINQ in C# but wanted to learn if it would be possible with streams introduced in Java 8.

C# would be something like this:

// seperate out items into two lists (processingTypeOneItems, processingTypeTwoItems)
...

// join items
var joinedItems =
    from i in processingTypeTwoItems
    join j in processingTypeOneItems on i.id equals j.appliedToItemId into gj
    from item in gj.DefaultIfEmpty()
    select new { id = i.id, chargeAmount = i.chargeAmount, discountAmount = item?.chargeAmount ?? 0 }; 

As can be seen, the items are matched on i.id == j.appliedToItemId and then the objects are merged into an object of anonymous type. I am really confused since most examples I have seen simply group by one attribute.

Is it possible in Java to group in this custom manner where the value of one attribute is compared to the value of another attribute?



Solution 1:[1]

        var joinedItems = processingTypeTwoItems.stream()
                .map(item -> new Item() {{
                        id = item.id;
                        processingType = item.processingType;
                        appliedToItemId = item.appliedToItemId;
                        chargeAmount = processingTypeOneItem.stream().filter(i -> i.appliedToItemId.equals(item.id)).findFirst().orElse(new Item() {{chargeAmount = 0.0f;}}).chargeAmount;
                    }}).collect(Collectors.toList());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Falah H. Abbas