Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Max number from List of String numbers using Java Streams

I am trying to get max number among List of Strings.

My code is:

List<String> list = new ArrayList<String>();
list.add("00657");
list.add("00632");
list.add("00656");
list.add("01125");

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

Above code is giving an error. Error is: Uncompilable source code - Erroneous sym type: java.util.stream.Stream.mapToInt.max. I should get 1125 as a result. I tried different ways but none of them is working.

like image 719
Abdusoli Avatar asked Jun 08 '26 07:06

Abdusoli


2 Answers

You need to parse the Strings as Integers which can be done using parseInt:

List<String> list = new ArrayList<>();
list.add("00657");
list.add("00632");
list.add("00656");
list.add("01125");

int maxNum = list.stream()
        .mapToInt(Integer::parseInt)
        .max()
        .orElse(-1);

Because there are no guarantees your stream is not going to be empty, this is why the orElse is needed.

like image 176
Marcio Lucca Avatar answered Jun 10 '26 17:06

Marcio Lucca


mapToint does not map any object (such as String) to an integer. It is used to map Integer type streams to int stream.

You need to first map the String numbers to Integer using map with parseInt and then map the Integer to int.

Use the following piece of code:

  Integer maxNum = list.stream()
                        .map(Integer::parseInt)
                        .mapToInt(Integer::intValue)
                       .max()
                       .getAsInt();

Hope this helps!

like image 34
anacron Avatar answered Jun 10 '26 18:06

anacron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!