Find Max number from List of String numbers using Java Streams

Viewed 1948

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.

5 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.

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!

@Abdusoli mapToInt can map only int type of data so you have to parse it into int first and final result is OptionalInt so it should be convert into Int. You can try both the way

First approach

Integer maxNum = list.stream()
                .mapToInt(Integer::parseInt)
                .max()
                .getAsInt();
        System.out.println(maxNum);

Second approach

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

intValue is not a static method,you should use Integer::parseInt instead. Also, max() return OptionalInt not Integer, you can use max().getAsInt(); or max().orElse();

Such as

Integer maxNum = list.stream().mapToInt(Integer::parseInt).max().getAsInt();
   Integer maxNum = list.stream()
            .map(Integer::valueOf).mapToInt(v-> v)
            .max().orElseThrow(NoSuchElementException::new);

You can try this one instead of intValue change to valueOf

Related