Best way to find the maximum integer inside an array of strings?

String[] array = new String[] {"1", "2", "3", "25"};

I want to find the maximum number inside this string and return it as integer.

What is the best way, especially regarding performance, since I have to parse several million lines with it?

Two solutions that I can think of:

Arrays.stream(array).mapToInt(Integer::parseInt).max().orElse(0);
Integer.valueOf(Collections.max(Arrays.asList(array))); //.max returns 0 when empty array
+4
source share
1 answer

Assuming the integers represented as Stringare non-negative and do not have trailing zeros, you do not need to parse them during the search. Use a custom comparator that first compares the strings by length and then by value:

import static java.util.Comparator.*;
//...

String[] s = {"1", "2", "3", "25"};
Optional<String> max = Stream.of(s).max(comparingInt(String::length).thenComparing(naturalOrder()));
int maxInt = Integer.parseInt(max.get());
+5
source

All Articles