3

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.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
shadab
  • 207
  • 1
  • 3
  • 12
  • 3
    Can't help without the definition of the object, which method it has, etc. And you haven't shown us your code and where you got confused. – RealSkeptic Nov 03 '16 at 07:44
  • 1
    Also, you did not specify the filter criteria. Which object should be returned if there are multiple objects with the same root id? – Turing85 Nov 03 '16 at 07:47

3 Answers3

3

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]]
Saravana
  • 12,647
  • 2
  • 39
  • 57
  • Thanks for the answer. – shadab Nov 03 '16 at 09:27
  • How to do grouping on additional column from the same Data object. I mean I introduced variables extensionId and repositoryId. I want to group on these 3 columns. something like `objects.stream().collect(Collectors.groupingBy(Data::(getRootId,getExtensionId,getrepositoryId), Collectors .collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Data::getVersion)), Optional::get)));` – shadab Nov 03 '16 at 15:27
0

You can use

.stream().collect(Collectors.groupingBy(Class::property));
Jerome Anthony
  • 7,823
  • 2
  • 40
  • 31
0
.stream().filter((item) -> {
     System.out.println(item); //this is element from your collection
     boolean isOk = true; //change true to your conditional
     return isOk;
})
Maciej Treder
  • 11,866
  • 5
  • 51
  • 74