if statement - Java equivalent of C#'s 'Enumerable.Any' -


in c# there way of reducing length of if-statement using enumerable.any check if elements in sequence satisfy condition (https://msdn.microsoft.com/en-us/library/vstudio/bb534972%28v=vs.100%29.aspx).

for example instead of:

if ( string.contains(">") || string.contains("<") || string.contains("&") || string.contains("l") || string.contains("p") ) 

we can use

if (new [] { ">", "<", "&", "l", "p"}.any(w => string.contains(w))) 

is there equivalent, if not better, way of doing in java?

with java 8 can write like:

if (stream.of(">", "<", "&", "l", "p").anymatch(string::contains)) {   ... } 

out of curiosity ran benchmark compare method vs regex. code , results below (lower score = faster). streams perform order of magnitude better regex.

benchmark                                    (s)  mode  samples     score    error  units c.a.p.so30940682.stream   >aaaaaaaaaaaaaaaaaaaaa  avgt       10    49.942 ±  1.936  ns/op c.a.p.so30940682.stream   aaaaaaaaaaaaaaaaaaaaa>  avgt       10    54.263 ±  1.927  ns/op c.a.p.so30940682.stream   aaaaaaaaaaaaaaaaaaaaap  avgt       10   131.537 ±  4.908  ns/op c.a.p.so30940682.stream   paaaaaaaaaaaaaaaaaaaaa  avgt       10   129.528 ±  7.352  ns/op c.a.p.so30940682.regex    >aaaaaaaaaaaaaaaaaaaaa  avgt       10   649.867 ± 27.142  ns/op c.a.p.so30940682.regex    aaaaaaaaaaaaaaaaaaaaa>  avgt       10  1047.122 ± 89.230  ns/op c.a.p.so30940682.regex    aaaaaaaaaaaaaaaaaaaaap  avgt       10  1029.710 ± 61.055  ns/op c.a.p.so30940682.regex    paaaaaaaaaaaaaaaaaaaaa  avgt       10   694.309 ± 32.675  ns/op 

code:

@state(scope.benchmark) @benchmarkmode(mode.averagetime) public class so30940682 {    @param({">aaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaa>",           "aaaaaaaaaaaaaaaaaaaaap", "paaaaaaaaaaaaaaaaaaaaa"}) string s;    @benchmark public boolean stream() {     return stream.of(">", "<", "&", "l", "p").anymatch(s::contains);   }    @benchmark public boolean regex() {     return s.matches("^.*?(>|<|&|l|p).*$");   } } 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -