How to do multiple finds with Java 8 stream? -
given following data structure:
class address contains:
addressid primary key type can "mail" or "legal" address text field containing address personid foreign key person class
scenario 1 pseudo code:
list<address> addresses = new list<address>(); addresses.add(new address(1,"mail","123 main st",1)); addresses.add(new address(2,"legal","456 main st",1)); //in scenario want "mail" record returned addresses.stream().filter(e->e.gettype().equals("mail")).findfirst().orelse(...);
scenario 2 pseudo code:
list<address> addresses = new list<address>(); addresses.add(new address(1,"legal","891 main st",2)); //in scenario want "legal" record returned addresses.stream().filter(e->e.gettype().equals("mail")).findfirst().orelse(...);
scenario 3 pseudo code:
list<address> addresses = new list<address>(); //in scenario null or empty optional returned addresses.stream().filter(e->e.gettype().equals("mail")).findfirst().orelse(...);
much appreicated if can out stream line of code above can handle 3 scenarios.
if list of address objects not big group them in hashmap:
list<address> addresses = getaddressesfromstream(); // populate list address objects // populate hashmap map<string, list<address>> typemap = new hashmap<string, list<address>>(); (address address: addresses) { string type; if (stringutils.isblank(address.gettype())) { type = "empty"; } else { type = address.gettype(); } list<address> group; if (!typemap.containskey(type)) { group = new arraylist<address>(); typemap.put(type, group); } group = typemap.get(type); group.add(address); }
hope fits problem.
Comments
Post a Comment