Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #33855
| From | Eric Sosman <esosman@comcast-dot-net.invalid> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: stream filter twice |
| Date | 2016-02-20 08:16 -0500 |
| Organization | A noiseless patient Spider |
| Message-ID | <na9oq9$abg$1@dont-email.me> (permalink) |
| References | <04334e10-3bad-49dc-87d8-dc2f00f90807@googlegroups.com> |
On 2/20/2016 7:28 AM, Philipp Kraus wrote:
> Hello,
>
> I'm using streams to filter some data. I just do this with
>
>
> List<myClass> x = myclasscollection.stream().filter( i -> i.filter() ).collect( Collectors.toList() );
> if (!x.isempty())
> return x;
>
>
> List<myClass> y = myclasscollection.stream().filter( i -> i.anotherfilter() ).collect( Collectors.toList() );
> if (!y.isEmpty())
> return y;
>
> return myclasscollection.stream().collect( Collectors.toList() );
>
> So my question is, can optimize this with a stream operation. I need to check each object of the collection, but only if no object exist, I need to run the check with another filter.
> A change to filter( i -> i.filter() || i.anotherfilter() ) or filter( i-> i.filter() ^ i.anotherfilter() ) is not possible, because I need the empty check of all results.
>
> In a best-case idea I need only one run with the stream and can build the result list in one shoot. Did you have got any idea to optimize this code?
I'm not sure it would count as an "optimization," but you could
use a grouping collector, something like
Map<Integer,List<myClass>> groups = myclasscollection.stream()
.collect(Collectors.groupingBy(
(i) -> i.filter() ? 1 : i.anotherfilter() ? 2 : 0);
if (!groups.get(1).isEmpty()) return groups.get(1);
if (!groups.get(2).isEmpty()) return groups.get(2);
However, this doesn't strike me as a good idea. The original looks
better, unless there are issues not known to me.
--
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM
Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
stream filter twice Philipp Kraus <philipp.kraus.flashpixx@gmail.com> - 2016-02-20 04:28 -0800
Re: stream filter twice Eric Sosman <esosman@comcast-dot-net.invalid> - 2016-02-20 08:16 -0500
Re: stream filter twice Arne Vajhøj <arne@vajhoej.dk> - 2016-02-20 22:20 -0500
Re: stream filter twice Robert Klemme <shortcutter@googlemail.com> - 2016-02-21 12:58 +0100
Re: stream filter twice Arne Vajhøj <arne@vajhoej.dk> - 2016-02-21 09:52 -0500
Re: stream filter twice Sebastian <news@seyweiler.dyndns.org> - 2016-02-22 00:13 +0100
csiph-web