简体   繁体   中英

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

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() .

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM