ObjectInputStreams { public static <X> ObjectInputStream<X> filter(final ObjectInputStream<X> unfiltered, final Predicate<X> keep) { return new ObjectInputStream<X>() { @Override public X readNext() { X result; do { result = unfiltered.readNext(); if (result == null) { return null; } } while (!keep.test(result)); return result; } @Override public void close() throws IOException { unfiltered.close(); } }; } protected  ObjectInputStreams(); static ObjectInputStream<X> filter(final ObjectInputStream<X> unfiltered, final Predicate<X> keep);  }
@Test public void alwaysTrue() { ObjectInputStream<Integer> out = ObjectInputStreams.filter(oneTwoThreeNull(), x -> true); assertThat(out.readNext(), is(1)); assertThat(out.readNext(), is(2)); assertThat(out.readNext(), is(3)); assertThat(out.readNext(), is(nullValue())); }
@Test public void alwaysFalse() { ObjectInputStream<Integer> out = ObjectInputStreams.filter(oneTwoThreeNull(), x -> false); assertThat(out.readNext(), is(nullValue())); }
@Test public void keepOne() { int toKeep = ThreadLocalRandom.current().nextInt(1, 4); ObjectInputStream<Integer> out = ObjectInputStreams.filter(oneTwoThreeNull(), x -> x.equals(toKeep)); assertThat(out.readNext(), is(toKeep)); assertThat(out.readNext(), is(nullValue())); }