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

1
  • And it doesn't work? If so, what fails? And generally ... where is your question? Commented Jul 31, 2017 at 8:31

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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) {

Comments

1

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

public static int smallestInt(int[] args) {
     return Arrays.stream(args).min().getAsInt();
}

Comments

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);
}

3 Comments

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 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
Yeah, that would be better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.