Java8 groupBy achieve the set of packets

Scene:
Java8 groupBy achieve the set of packets, a packet group by the similar Mysql function, a map is noted to give

1. Properties of individual packets in accordance with a set of
eg packet according skuId

Map <String, List <EntryDeliveryDetailywk >> detailsMap01 = dtos1.stream ()
.collect (Collectors.groupingBy (EntryDeliveryDetailywk :: getskuId));
1
2
2 a plurality of attributes according to the collection packet
splicing a plurality of solution a combination of an attribute property
the plurality of fields together into a new field, the grouping of groupBy use Java8

Map<String, List<EntryDeliveryDetailywk>> detailmap = details.stream()
.collect(Collectors.groupingBy(d -> fetchGroupKey(d) ));

fetchGroupKey String Private (EntryDeliveryDetailywk Detail) {
        return detail.getSkuId () toString ().
        + detail.getItemsName ()
        + detail.getWarehouseId () toString ().   
        + detail.getSupplierId () toString ();.
    }

Solution 2 made static internal class
configuration of static internal elements in the set class type (i.e., packet member variable corresponding to the plurality of attributes)
EG

// static inner class
class the Person {
    public static class NameAge {
        public NameAge (String name, int Age) {
            ...
        }

        // Note Implement override the equals method and the hash function MUST
    }

    public NameAge getNameAge() {
        return new NameAge(name, age);
    }
}

// grouping
the Map <NameAge, List <>> map = people.collect the Person (Collectors.groupingBy (the Person :: getNameAge));

Solution 3 nested calls Java8 groupby
Note also get a nested map

Map<String, Map<Integer, List<Person>>> map = people
    .collect(Collectors.groupingBy(Person::getName,
        Collectors.groupingBy(Person::getAge));

// Call
map.get ( "Fred") get ( 18);.

Reference
https://stackoverflow.com/questions/28342814/group-by-multiple-field-names-in-java-8#
 

Published 776 original articles · won praise 50 · Views 150,000 +

Guess you like

Origin blog.csdn.net/weixin_44018338/article/details/104982633