Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream API - Select the lowest key after group by

I have a stream of Foo objects.

class Foo {
    private int variableCount;
    public Foo(int vars) {
        this.variableCount = vars; 
    }
    public Integer getVariableCount() { 
      return variableCount; 
    }
}

I want a list of Foo's that all have the lowest variableCount.

For example

new Foo(3), new Foo(3), new Foo(2), new Foo(1), new Foo(1)

I only want the stream to return the last 2 Foos, since they have the lowest value.

I've tried doing a collect with grouping by

.collect(Collectors.groupingBy((Foo foo) -> {
                    return foo.getVariableCount();
})

And that returns a Map<Integer, List<Foo>> and I'm not sure how to transform that into what I want.

Thanks in advance

like image 998
James Kleeh Avatar asked Feb 27 '18 17:02

James Kleeh


1 Answers

You can use a sorted map for grouping and then just get the first entry. Something along the lines:

Collectors.groupingBy(
    Foo::getVariableCount,
    TreeMap::new,
    Collectors.toList())
.firstEntry()
.getValue()
like image 100
lexicore Avatar answered Oct 16 '22 04:10

lexicore