1
public static int getMin(int[] arr, int min,int max,int a){
 Integer[] test = Arrays.stream(arr).boxed().toArray(Integer[]::new);
 List<Integer> list =null;
 list = new ArrayList(Arrays.asList(test));
 list.removeAll(Collections.singleton(0));
 min = Collections.min(list);
 max = Collections.max(list);
 if(a == 0) {
 return min;
 } else {
 return max;
 }
}

List item

Exception in thread "main" java.util.NoSuchElementException
 at java.util.ArrayList$Itr.next(ArrayList.java:862)
 at java.util.Collections.min(Collections.java:596)
 at Solution.getMin(Solution.java:47)

What is the reason for this exception?

djm.im
3,3334 gold badges32 silver badges47 bronze badges
asked May 23, 2020 at 5:02
3
  • How many non-0 elements does your list have? Commented May 23, 2020 at 5:03
  • it depends on input, and for that question inputs are given on runtime Commented May 23, 2020 at 5:21
  • 1
    As a side note, this is a horribly inefficient way to get the minimum or maximum from an array. Your very first line does already contain a Stream operation, so why not let the Stream return the intended result in the first place: IntStream is = Arrays.stream(arr).filter(i -> i != 0); OptionalInt result = a == 0? is.min(): is.max(); Then, you have to decide what to do if the result is empty, e.g. return result.orElse(0); Commented May 24, 2020 at 10:37

2 Answers 2

1

Empty collection

The Javadoc for Collections.min states that passing an empty collection will throw a NoSuchElementException.

Add a test for List::isEmpty before checking the minimum and maximum.

answered May 23, 2020 at 6:07
Sign up to request clarification or add additional context in comments.

Comments

1

You passed an array that contains only zeros. And this line of code removes all zero elements list.removeAll(Collections.singleton(0));. After this, the list has size zero - no any elements in it.


Here is an example to reproduce the exception

private static void getMin() {
 List<Integer> list = new ArrayList<>();
 Collections.min(list);
}
answered May 23, 2020 at 6:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.