Searching Lists of Custom Employee Objects each based on first name and last name in Java -
after doing lots of research on stackoverflow, found solution searching based on 1 attribute using overriding equals()
method.
my question is: have list of employee objects containing first name, last name , employee ids.
arraylist.stream().filter() work java 8. need solution can work java 7.
suppose, there 10 employee objects first , last names as:
jam jon1 [note: first name : jam , last name : jon1]
jam jon2
jam jon3
jam jon4
jam jon5
pam jin
pam jin
pam jin
pam jin
pam jin
now, have 1 input i.e. jam.
i want list of employee objects containing jam first name.
now, have input i.e. jin.
i want list of employee objects containing jin last name.
i have 500 employee objects in arraylist.
employee class:
public class employee{ string firstname; string lastname; employee(string firstname, string lastname){ this.firstname = firstname; this.lastname = lastname; } } employee emp1 = new employee("jam","jon1"); employee emp2 = new employee("jam","jon2"); employee emp3 = new employee("jam","jon3"); employee emp4 = new employee("jam","jon4"); employee emp5 = new employee("jam","jon5"); employee emp6 = new employee("pam","jin"); employee emp7 = new employee("pam","jin"); employee emp8 = new employee("pam","jin"); employee emp9 = new employee("pam","jin"); employee emp10 = new employee("pam","jin");
what best way find list of employee objects has "jam" first name , list of employee objects has "jin" last name.
hashmap<string, list<employee>> firstnamecollected = new hashmap<>(); (employee e : yourarraylist) { if (!firstnamecollected.containskey(e.firstname)) firstnamecollected.put(e.firstname, new arraylist<employee>()); firstnamecollected.get(e.firstname).add(e); } set<list<employee>> firstnameset = new hashset<>(); firstnameset.addall(firstnamecollected.values());
Comments
Post a Comment