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

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>());

Group truck by truckType - stream

trucksByType =;

Group truck by truckType -

ImmutableListMultimap<String, ImmutableList<Truck>> trucksByType = Multimaps.index(
    trucks, { Truck t -> return t.getTruckType() }

See here for reference