Collectors collect a list of pair in java

1.1k views Asked by At

I got a list of pairs that I want to sorted by the left field, I succeed to do it and to get the 25 first element but now the problem is that I want to collect the right element into a list (or even both of them) but I don't know how to do it there is a problem with the toList().

return listOfTokens.stream()
        .sorted((o1, o2) -> Double.compare(o1.getLeft().getCompare(terms.field.docCount),
                                           o2.getLeft().getTfIdf(terms.fielddocCount)))
        .limit(25)
        .collect(toList());
1

There are 1 answers

3
Eran On BEST ANSWER

If you want to collect just the right element, use map :

return listOfTokens.stream()
.sorted((o1, o2) -> Double.compare(o1.getLeft().getCompare(terms.field.docCount), o2.getLeft().getTfIdf(terms.fielddocCount)))
        .limit(25)
        .map(o -> o.getRight())
.collect(toList());

If you want to collect both the right and left:

return listOfTokens.stream()
.sorted((o1, o2) -> Double.compare(o1.getLeft().getCompare(terms.field.docCount), o2.getLeft().getTfIdf(terms.fielddocCount)))
        .limit(25)
        .flatMap(o -> Stream.of(o.getLeft(),o.getRight()))
.collect(toList());