Heist
Heist

Reputation: 45

Using a variable outside of forEach loop

I'm new to java and I'm tinkering with forEach loops.

I want to use entry.getValue() outside of the loop like this:

hashmap.entrySet().stream()
    .sorted(Map.Entry<String,Double>comparingByValue())
    .limit(1).forEach(entry->
        {System.out.print("Worst output: " + entry.getValue() + ");}
    );
....//print the one iteration of previous loop, or use entry.getValue() as var

Upvotes: 1

Views: 2214

Answers (3)

Buhb
Buhb

Reputation: 7149

If you want to do something with the entire Map.Entry, and also elegantly handle empty maps, I suggest you do it with Optional.

Optional<Map.Entry<String, Double>> o = hashmap.entrySet().stream().min(Map.Entry.comparingByValue());
o.ifPresent(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));

This way, if there is at least one entry in the map, the lowest one is returned, and since it's wrapped in an optional, you can easily handle the empty case as well. In the sample code above, it will print both the key and the value, if it's present, or do nothing if it isn't.

Upvotes: 2

Mureinik
Mureinik

Reputation: 312329

You could simply use the max method to get the highest value:

Double max = hashmap.values()
                    .stream()
                    .max(Comparator.naturalOrder())
                    .orElse(null);

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201537

I believe you want to map your entries to double and then use DoubleStream.min() with something like,

double worst = hashmap.entrySet().stream()
        .mapToDouble(Map.Entry<String,Double>::getValue).min().getAsDouble();
System.out.println("Worst output: " + worst);

If you actually want the maximum value use max() instead of min().

Upvotes: 3

Related Questions