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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With