How to group List based on an class attribute in java

Viewed 36

I am trying to group Foo based on orderId, but I see multiple entries for the same orderId. We have duplicates for the same orderId, how to prevent that

    Map<Long, List<Foo>> tOrders = new HashMap<Long, List<Foo>>();
    for (Foo foo : foos) {
        Long orderId = foo.getOrderId();
        if (tOrders.containsKey(orderId)) {
            List<Foo> tFoos = tOrders.get(orderId);
            tFoos.add(foo);
        }   
        else {
            List<Foo> nFoos = new ArrayList<Foo>();
            nFoos.add(foo);
            tOrders.put(orderId, nFoos);
        }   
    }
0 Answers
Related