8

I have a Map<Float, String> and would like to get the maximum of all keys. In C# I would do something like this:

var dictionary = new Dictionary<float, string>{{5,"foo"}, {42, "bar"}, {0, "foobarz"}};
float max = dictionary.Max(x => x.Key); //42

Now I'm looking for a way to do the same using Java 8 lambdas, but the closest I got is:

float max = (float)map.keySet().stream().mapToDouble((x) -> x).summaryStatistics().getMax();

This looks awful and requires completely unnecessary type casts. Is there a better way to do this?

2 Answers 2

14

The interface Stream contains the method max to get the maximum element. You can use a method reference as Comparator. The method max returns an Optional<Float>, because there is no maximum element in an empty stream. You can use the method orElse to provide an alternative value for this case.

float max = map.keySet().stream().max(Float::compareTo).orElse(0.0f);
5
  • Float contains also compare(x,y) so you can also use Float::compare
    – Pshemo
    May 23, 2014 at 15:32
  • @Pshemo: True. However, compare uses primitive types whereas compareTo uses the wrapper types. In this case, I prefer the latter, because the code is already working with wrapper types (i.e. avoid boxing/unboxing).
    – nosid
    May 23, 2014 at 15:34
  • OK, I see your point. Unboxing means Float.compare(foo.floatValue(), bar.floatValue()) while foo.compareTo(bar) returns Float.compare(this.value, bar.value). It means that in first case we are invoking floatValue() twice to get value while in second case we can skip it because we have direct access to value. Thanks, I learned something new today :)
    – Pshemo
    May 23, 2014 at 15:47
  • 2
    @nosid Do you think there would be any performance difference in practice? I would expect that the calls of floatValue() would be inlined, resulting in the same code once it has been JIT'd. May 23, 2014 at 16:29
  • 1
    @MauriceNaftalin: No, I don't think performance is an issue. I think it is good style not to introduce unnecessary, implicit type conversions.
    – nosid
    May 23, 2014 at 16:57
14

There's a more direct solution than operating on the keySet(); operate directly on the entrySet() using the comparator factories added to Map.Entry.

Map.Entry<K,V> maxElt = map.entrySet().stream()
                           .max(Map.Entry.comparingByKey())
                           .orElse(...);

This permits not only getting min/max elements, but also sorting, so its easy to find the top ten key/value pairs like this:

Stream<Map.Entry<K,V>> topTen = map.entrySet().stream()
                                   .sorted(Map.Entry.byKeyComparator().reversed())
                                   .limit(10);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.