1

I'm trying to get the min value of an array of int with streams, I'm trying to do something like:

public static int smallestInt(int[] args) {
    return Arrays.stream((Arrays.stream(args)
                .boxed().toArray( Integer[]::new ))
                .mapToInt(Integer::intValue).min().getAsInt;
}

My question is what's the best way to do it?

PS: There's a similar question but without sterams here Finding the max/min value in an array of primitives using Java

Levy Moreira
  • 2,733
  • 2
  • 14
  • 10

4 Answers4

6

You're over-complicating it.

IntStream.of(args).min().getAsInt()

Note: this will throw a NoSuchElementException if the array is empty, which is probably a desirable result.

Michael
  • 41,989
  • 11
  • 82
  • 128
2

I think you're using too much streams.

It will just do so:

int theMin = Arrays.stream(args).min().getAsInt();

As the method parameter args is already an array of integers according to the method signature:

public static int smallestInt(int[] args) {
Mario Santini
  • 2,905
  • 2
  • 20
  • 27
1

You may just use, it's easier to understand and proper :

public static int smallestInt(int[] args) {
     return Arrays.stream(args).min().getAsInt();
}
azro
  • 53,056
  • 7
  • 34
  • 70
1

Most others have provided good solutions, but they didn't cover the case of no smallest value at all, this should cover that case too:

public static int smallest(int[] ints){
    return Arrays.stream(ints).min().orElse(Integer.MIN_VALUE);
}
Lino
  • 19,604
  • 6
  • 47
  • 65
  • 5
    I don't like that solution. How do I, as a caller of this function, know whether the smallest int in my array *was* `Integer.MIN_VALUE`, or whether the array was empty? The correct thing to do if the array is empty is to throw an exception, which `getAsInt` already does. – Michael Jul 31 '17 at 08:44
  • 1
    @Michael you have a point. Maybe it's better to return the IntOptional directly, then the caller can decide himself what happens when no value is present – Lino Jul 31 '17 at 08:53
  • Yeah, that would be better. – Michael Jul 31 '17 at 08:57