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

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

What is the best way, especially with regards to performance as I have to parse a few million rows with it?

Two solutions 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
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • 6
    The first one allows to parallelize easily the stream if needed. But your second implementation is wrong, so I supposed you didn't tested it. So before thinking of the "best" way, you should think of the "correct" way. – Alexis C. May 05 '15 at 09:01
  • 1
    It seems that the second way is just wrong: it compares strings and just then parses the result to `int`. This means for example that 2 > 10 – AlexR May 05 '15 at 09:02
  • possible duplicate of [Finding the max/min value in an array of primitives using Java](http://stackoverflow.com/questions/1484347/finding-the-max-min-value-in-an-array-of-primitives-using-java) – MrSimpleMind May 05 '15 at 09:03
  • As you (or a library you chose) have to parse the string to an int before getting the max from a collection/stream etc. performance should be measured on the OS/JVM you are using. Another question is, if you can read the rows in another way than a String array - depending on the format. – swinkler May 05 '15 at 09:13
  • You are asking for the best way. I think this is subject to opinion unless you get actual data and as @swinkler said it may depend on external factors. Just benchmark it yourself. But the Sasha comment is a good idea. I would try it. – aalku May 05 '15 at 09:39

1 Answers1

6

Supposed that integers presented as Strings are all non-negative and don't have trailing zeros, you don't need to parse them during the search. Use a custom comparator, which first compares strings by length, 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());
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67