java - Dynamically filter List with Predicate -


i have following list of strings:

{"new york","london","paris","berlin","new york"}

i trying use guava library , want filter list in such way strings equal string provide. if had fixed value let's "new york" following:

predicate<string> mycity = new predicate<string>() {     @override public boolean apply(string city) {         return city == "new york";     }                }; 

but if want return statement :

return city == mystringvariable

can give argument city predicate or combine 2 predicates somehow ?

either use final string or subclass of predicate :

final string teststr = textbox.gettext(); //for example predicate<string> mycity = new predicate<string>() {     @override public boolean apply(string city) {         return city.equals(teststr);     }                }; 

or

public class citypredicate implements predicate<string>{     string cityname;     public citypredicate(string cityname){         this.cityname = cityname;     }     @override public boolean apply(string city) {         return city.equals(cityname);     }  } //use example : predicate<string> mycity = new citypredicate("new york"); 

and @sotirios delimanolis told you, compare string equals()

edit : example frank pavageau's solution : given class :

public class city{     string cityname;     public city(string cityname){         this.cityname=cityname;     }      @override     public boolean equals(object obj) {         if(obj instanceof string){             return cityname.equals(obj);         }         return false;     } }  list<city> cities =  lists.newarraylist(new city("new york"),new city("chicago")); predicate<string> mycitypredicate = predicates.equalto("new york"); final list<city> res = lists.newarraylist(iterables.filter(cities , mycitypredicate)); //res.size() 1 , containing city("new york") //to check whether present can : final boolean isin = predicates.in(cities).apply("new york"); 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -