Java group list objects by attribute
How to group a list of objects by one of the object’s attribute, which is similar to SQL group by statement and having the same results.
Object example
@Data
class Truck {
private Integer id;
private String plateNumber;
private String truckType; // 5t, 8t, 11t, and etc.
private Integer loadCapacity;
}
List<Truck> trucks = findAll(); // get a list of Truck objects
Group truck by truckType - for loop
Map<String, List<Truck>> trucksByType = new HashMap<String, List<Truck>>();
for (Truck truck: trucks) {
String truckType = truck.getTruckType();
if (!trucksByType.containsKey(truckType)) {
trucksByType.put(truckType, new ArrayList<Truck>());
}
trucksByType.get(truckType).add(truck);
}
Group truck by truckType - stream
trucksByType = trucks.stream().collect(Collectors.groupingBy(Truck::getTruckType()));
Group truck by truckType - com.google.common.collect.Multimaps
ImmutableListMultimap<String, ImmutableList<Truck>> trucksByType = Multimaps.index(
trucks, { Truck t -> return t.getTruckType() }
);
See here for reference