shadab shadab - 1 month ago 8
Java Question

How to use Java streams for the filtering

I have a list of object which has 3 variables(id, version, root_id)

Eg : {(1, 3, 1001),(2,2,1001), (3,1,1001), (4,1,1002), (5,1,1003)}


I want to retain only 1 object having same root_id and having highest version number.

output : {(1, 3, 1001),(4,1,1002), (5,1,1003)}


How can I apply the java stream filter on the list to get the desired output.
Please help. I am getting a bit confused on applying the filter.

Answer

you need to group by rootId and take the max version by comparing int value.

maxBy returns Optional data, to unwrap the actaul data collectingAndThen is used

public static void main(String[] args) {

    List<Data> objects = Arrays.asList(new Data(1, 3, 1001), new Data(2, 2, 1001), new Data(3, 1, 1001),
            new Data(4, 1, 1002), new Data(5, 1, 1003));

    Map<Integer, Data> filtered = objects.stream().collect(Collectors.groupingBy(Data::getRootId, Collectors
            .collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Data::getVersion)), Optional::get)));

    System.out.println(filtered.values());
}

static class Data {
    int id;
    int version;
    int rootId;

    //getter,setter & constructors
    //toString
}

output

[Data [id=1, version=3, rootId=1001], Data [id=4, version=1, rootId=1002], Data [id=5, version=1, rootId=1003]]