Given a starting List<Foo>
, what is the most concise way to determine if a Foo
element having a property bar
(accessed by getBar()
) has a value of "Baz
"? The best answer I can come up with is a linear search:
List<Foo> listFoo;
for(Foo f:listFoo) {
if(f.getBar().equals("Baz")) {
// contains value
}
}
I looked into HashSet but there doesn't seem to be a way to use contains()
without first instantiating a Foo
to pass in (in my case, Foo
is expensive to create). I also looked at HashMap, but there doesn't seem to be a way to populate without looping through the list and adding each Foo
element one at a time. The list is small, so I'm not worried about performance as much as I am clarity of code.
Most of my development experience is with C# and Python, so I'm used to more concise statements like:
// C#
List<Foo> listFoo;
bool contains = listFoo.Count(f => f.getBar=="Baz")>0;
or
# Python
# list_foo = [Foo(), ...]
contains = "Baz" in (f.bar for f in list_foo)
Does Java have a way to pull this off?