简体   繁体   中英

Stateful dependent Filtering a stream

indicesArrays.stream().flatMap(n -> n.indices).sorted().filter(x->
//filter x if its difference with its predecessor is less then 5;
)

Is there a "natural" way to do this kind of dependent filtering on a stream? How would you do it right?

Thats how I would try:

indicesArrays.stream().flatMap(n -> n.indices).sorted().filter(new Predicate<Integer>() {
                Integer lastX = null;

                @Override
                public boolean test(Integer t) {
                    if (lastX == null) {
                        lastX = t;
                        return true;
                    }
                    final boolean include = t - lastX >= 5;
                    lastX = t;
                    return include;
                }
            });

But I'm not sure if that's a good approach neither am I sure it would always work...

This, in your particular case and for the latest openjdk release at the time (jdk+b132), will work,bbut it's not recommended. Because your indexArrays are very likely to be a Collection<SomeClassWithABoxedIntStreamField> , whose stream() method return a sequential stream, then no interference may be created.

However, if indexArrays.stream() returns a parallel stream, you will first have to turn it into a sequential stream with Stream::sequential . Working on that stream may gives the right result.

Anyway, this kind of code is really not recommended and may not be compatible with future Java releases, it break the contract, too.

PS: take a look at IntStream and Stream::flatMapToInt . They can wipe the cost of boxing and unboxing integer values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM