java - How to negate a method reference predicate -


in java 8, can use method reference filter stream, example:

stream<string> s = ...; int emptystrings = s.filter(string::isempty).count(); 

is there way create method reference negation of existing one, i.e. like:

int nonemptystrings = s.filter(not(string::isempty)).count(); 

i create not method below wondering if jdk offered similar.

static <t> predicate<t> not(predicate<t> p) { return o -> !p.test(o); } 

there way compose method reference opposite of current method reference. see @vlasec's answer below shows how explicitly casting method reference predicate , converting using negate function. 1 way among few other not troublesome ways it.

the opposite of this:

stream<string> s = ...; int emptystrings = s.filter(string::isempty).count(); 

is this:

stream<string> s = ...; int notemptystrings = s.filter(((predicate<string>) string::isempty).negate()).count() 

or this:

stream<string> s = ...; int notemptystrings = s.filter( -> !it.isempty() ).count(); 

personally, prefer later technique because find clearer read it -> !it.isempty() long verbose explicit cast , negate.

one make predicate , reuse it:

predicate<string> notempty = (string it) -> !it.isempty();  stream<string> s = ...; int notemptystrings = s.filter(notempty).count(); 

or, if having collection or array, use for-loop simple, has less overhead, , *might **faster:

int notempty = 0; for(string s : list) if(!s.isempty()) notempty++; 

*if want know faster, use jmh http://openjdk.java.net/projects/code-tools/jmh, , avoid hand benchmark code unless avoids jvm optimizations — see java 8: performance of streams vs collections

**i getting flak suggesting for-loop technique faster. eliminates stream creation, eliminates using method call (negative function predicate), , eliminates temporary accumulator list/counter. few things saved last construct might make faster.

i think simpler , nicer though, if not faster. if job calls hammer , nail, don't bring in chainsaw , glue! know of take issue that.

wish-list: see java stream functions evolve bit java users more familiar them. example, 'count' method in stream accept predicate can done directly this:

stream<string> s = ...; int notemptystrings = s.count(it -> !it.isempty());  or  list<string> list = ...; int notemptystrings = lists.count(it -> !it.isempty()); 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -