java - Find first matching string in two lists in less than O(n^2) time using a Java8 one-liner -
simple question, have 2 arrays / lists, i'm looking efficient one-liner in java8 match first argument against long list of possible arguments.
arguments public static void main(string... args)
, other 1 list of predefined strings i'll call secondarray, ["a", "b", "cc", "de", ...]
. want match 2 incoming arrays against each other , find first matching arg
ument against secondarray
list.
example: args = arrays.aslist("r", "b", "c", "d", ...)
secondlist = arrays.aslist("q", "z", "x", "c", "d", ...)
the first matching argument "c"
the java7 (inefficient) way of doing have been:
string profile = "default"; (string arg : args){ if (secondarray.contains(arg)){ profile = arg; break; } } dosomethingwith(profile);
in java8, i've done far, wondering if there's better way (more efficient, faster, etc - let's assume both args , secondarray can potentially contain 100k entries):
string profile = arrays.stream(args) .filter(secondarray::contains) .findfirst() .orelse("default"); dosomethingwith(profile);
my assumption filter doing secondarray::contains
mean o(n^2) complexity, since secondarray.contains(arg)
called each of arguments. closer o(n) while still maintaining single line of java8 i'm after.
the trick make 1 liner create set in filter cause
string profile = arrays.stream(args) .filter(new hashset(secondlist)::contains) .findfirst() .orelse("default");
such set going created once. same instance of set used each item in args.
so code o(n)
create set , o(n)
finding first arg.
just keep in mind expanded lambda like
.filter(arg -> new hashset(secondlist).contains(arg))
will create set each argument , blowup complexity o(n^2)
.
Comments
Post a Comment