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
2 Answers 2
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
Basil Bourque
347k130 gold badges951 silver badges1.3k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
djm.im
3,3334 gold badges32 silver badges47 bronze badges
Comments
lang-java
0elements does your list have?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);