DigitalSelf
DigitalSelf

Reputation: 9

How to filter out a range of numbers from another range

I'm trying to create an IntStream in Java 8, from which I'd like to filter out another range. For instance, if I have the following array :

{1, 2, 3, 4, 5, 6, 7, ..., 20}

I'd like to keep all except: {4, 5, 6, 7}

I created the following IntStream:

IntStream.rangeClosed(1, 20);

However, I'd like the possibility of doing some kind of :

IntStream.rangeClosed(1, 20).filter(IntStream.rangeClosed(4, 7));

Is there a way to do so? Apparently, there's no way to do that, but I may be mistaken. Thanks in advance for any reply

Upvotes: 0

Views: 933

Answers (2)

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

Why not just make two streams and concat? 1-3 and 8-20?

IntStream.concat(IntStream, IntStream)

By doing that you skip the checking for each element.

Another suggestion is to convert it to two sets and do

range1.boxed().collect(Collectors.toSet());
range2.boxed().collect(Collectors.toSet());

range1.removeAll(range2);

Upvotes: 1

shmosel
shmosel

Reputation: 50726

What's wrong with a simple range check?

IntStream.rangeClosed(1, 20).filter(i -> i < 4 || i > 7)

Upvotes: 4

Related Questions