How to find maximum value from a Integer using stream in Java 8?
Asked Answered
G

11

123

I have a list of Integer list and from the list.stream() I want the maximum value.

What is the simplest way? Do I need comparator?

Gyrostat answered 13/7, 2015 at 8:10 Comment(2)
Read the javadoc: docs.oracle.com/javase/8/docs/api/java/util/stream/…, docs.oracle.com/javase/8/docs/api/java/util/…Philistine
You may have your reasons to use a Stream, but don't forget Collections.max..Goldiegoldilocks
Q
264

You may either convert the stream to IntStream:

OptionalInt max = list.stream().mapToInt(Integer::intValue).max();

Or specify the natural order comparator:

Optional<Integer> max = list.stream().max(Comparator.naturalOrder());

Or use reduce operation:

Optional<Integer> max = list.stream().reduce(Integer::max);

Or use collector:

Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));

Or use IntSummaryStatistics:

int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();
Quarto answered 13/7, 2015 at 8:41 Comment(9)
Would be interesting to know which one is more efficient.Fucoid
May I ask why, Tagir?Marlenamarlene
@elect, it first unboxes all the integers, then compares the unboxed ones. 2nd, 3rd and 4th solutions do the unboxing on each comparison effectively doing twice as much unboxing operations. The last one computes more statistics (like sum and min) which is unnecessary here, but will surely take some time.Quarto
If you want to just get an int, then mapToInt(...).max().getAsInt() or reduce(...).get() to the method chainsFaction
Hi. What about having nulls in the input list? If you put List<Integer> list = Arrays.asList(null, 9, 11, 7, 5, null); then each of proposed options failsCimabue
@Bogdan, this is solveable, though apparently was not required in question. Nevertheless you can post your own answer covering this situation.Quarto
Java lambda streams are so bad designed and not intuitive. They should at least overload list.stream().max() using the default natural order comparator. Honestly all above options are shit to write, read and remember from a developer point of view. Thats why i come back to the same lambda questions all the time in java my daily language. Just compare same things with c# which i not even work a day per month in and dont even need to lookup things so easy is their lambda. Java messed up big again similar to Date API and now we are stuck.Onward
How do you know all these methods?Science
@Cimabue it's as simple as adding a filter to the stream: .filter(Objects::nonNull)Sachasachem
T
13
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
Thermolysis answered 22/10, 2015 at 6:33 Comment(2)
This works only, if all of your values are positive. Use Integer.MIN_VALUE instead of 0 in reduce().Household
Could also be int max = list.stream()reduce(Integer.MIN_VALUE, Integer::max);Schnapp
M
4

Another version could be:

int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
Minify answered 25/2, 2016 at 13:32 Comment(0)
C
4

Correct code:

int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));

or

int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
Curse answered 25/4, 2017 at 10:9 Comment(0)
U
3

You can also use below code snipped:

int max = list.stream().max(Comparator.comparing(Integer::valueOf)).get();

Another alternative:

list.sort(Comparator.reverseOrder()); // max value will come first
int max = list.get(0);  
Uis answered 10/4, 2019 at 14:12 Comment(0)
D
3
int value = list.stream().max(Integer::compareTo).get();
System.out.println("value  :"+value );
Dara answered 15/4, 2019 at 16:33 Comment(1)
There are other answers that provide the OP's question, and they were posted many years ago. When posting an answer, please make sure you add either a new solution, or a substantially better explanation, especially when answering older questions.Bedroom
A
3

I think another easy way is

IntSummaryStatistics statistics = List.of(1, 2, 3).stream()
             .mapToInt(Integer::intValue)
             .summaryStatistics();
int max = statistics.getMax();

 

With this you can also getMin() amd other stuff like mean. A SummaryStatistics Object can be created from other Streams by supplying appropriate parameters.

Ashy answered 21/12, 2022 at 13:6 Comment(0)
S
0

With stream and reduce

Optional<Integer> max = list.stream().reduce(Math::max);
Sociolinguistics answered 3/8, 2018 at 9:20 Comment(1)
It seems you posted this answer twice and removed the other one, but as I commented on the other one, this solution is already included in Tagir's answer (with Integer::max but that's exactly the same).Gare
E
0

you can also find the max element in a collection using bellow code:

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Optional<Integer> max = intList.stream().max((a, b) -> a - b);
Erudition answered 21/8, 2023 at 4:52 Comment(0)
S
0

In my case, need to convert a String (SeqNum) to integer and find a max value of it.

   list.stream().map(TxnCharges::getSeqNum)
                .max(Comparator.comparingInt(s -> Integer.parseInt(s.trim())))
                .orElse(null);
Subchaser answered 18/1 at 15:8 Comment(0)
P
-2

You could use int max= Stream.of(1,2,3,4,5).reduce(0,(a,b)->Math.max(a,b)); works for both positive and negative numbers

Photoemission answered 13/6, 2017 at 19:2 Comment(1)
You should start from Integer.MIN_VALUE to make it work with negative numbers.Gare

© 2022 - 2024 — McMap. All rights reserved.