LOUDKING
LOUDKING

Reputation: 321

stream and functional Interface: throw exception inside stream and aggregate them

I am new to stream and functional interface and just wonder if this requirement could be done via them. Given an array of integers, if any of them is negative, then do not process but instead throw exception containing all negative integers.

Example: INPUT = [0, -1, -2] 
EXPECTED Exception: invalid integers: (-1, -2).

I do know how to do that with a for loop but really curious if this can be achieved via stream and functional interfaces. So any help is appreciated.

int [] input = {0, -1, -2};
List<Integer> negatives = new LinkedList<>();

for (int i : input) {
    if (i < 0) {
        negatives.add(i);
    }
}

if (negatives.isEmpty() == false) {
    throw new IllegalArgumentException("Invalid integers: " + negatives);
}

Upvotes: 2

Views: 216

Answers (2)

azro
azro

Reputation: 54148

You can do as follow

public static void main(String[] args)  {
    List<Integer> list = Arrays.asList(1, 2, 3, -3, -2);
    checkList(list);
}

private static void checkList(List<Integer> list) {
    list.stream().filter(i -> i < 0).findFirst()
            .ifPresent(integer -> {
                throw new IllegalArgumentException("Invalid are" + 
                             Arrays.toString(list.stream().filter(i -> i < 0).toArray()));
            });
}

Which will give

Exception in thread "main" java.lang.RuntimeException: Invalid are[-3, -2]

Upvotes: 0

Michael
Michael

Reputation: 44150

I'd write it with a simple filter:

final List<Integer> invalid = Arrays.asList(0, -1, -2).stream()
    .filter(i -> i < 0)
    .collect(Collectors.toList());

if (!invalid.isEmpty()) throw new RuntimeException("Invalid integers " + invalid);

Upvotes: 3

Related Questions