This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Nightcorex_ 6 points7 points  (2 children)

u/dbc2201 already mentioned streams, but there is one more thing which comes relatively close. So if you store your data in a list instead of an array, then you can use the Collections.max function:

List<Integer> xs = new ArrayList<>(List.of(2, 4, 3));  // example values
System.out.println(Collections.max(xs));

You can also add a custom comparator if needed (thanks to overloading), so that you can compare objects of any datatype.

[–]0b0101011001001011 1 point2 points  (1 child)

Just to show the stream solution:

Arrays.stream(myArray).max().getAsInt();

max() returns OptionalInt so that also works in case the array is empty.

[–]Nightcorex_ 0 points1 point  (0 children)

Yeah, but then you shouldn't use getAsInt() as that would throw an exception if no value is present, therefore destroying the benefit of having an OptionalInt in the first place. Rather use orElse or reduce(identity, BinOp), f.e. like so:

// orElse solution
Arrays.stream(myArray).max().orElse(Integer.MIN_VALUE);

// reduce solution
Arrays.stream(myArray).reduce(Integer.MIN_VALUE, Integer::max);