lambda - Java 8 extract first key from matching value in a Map -


suppose have map of given name, surname pairs , want find given name of first entry in map has surname matching value. how in java 8 fashion.

in test case example below put 2 ways it.

however first 1 (looking given name of first person surname of "donkey") throw java.util.nosuchelementexception: no value present not safe.

the second 1 works not harder read it bit not quite functional.

just wondering if here suggest me easier clearer way of achieving using either stream() or foreach() or both.

@test public void shouldbeabletoreturnthekeyofthefirstmatchingvalue() throws exception {     map<string, string> names = new linkedhashmap<>();     names.put("john", "doe");     names.put("fred", "flintstone");     names.put("jane", "doe");     string keyofthefirst = names.entryset().stream().filter(e -> e.getvalue().equals("doe")).findfirst().get().getkey();     assertequals("john", keyofthefirst);      try {         names.entryset().stream().filter(e -> e.getvalue().equals("donkey")).findfirst().get();     } catch (nosuchelementexception e){         // expected     }      optional<map.entry<string, string>> optionalentry = names.entryset().stream().filter(e -> e.getvalue().equals("donkey")).findfirst();     keyofthefirst = optionalentry.ispresent() ? optionalentry.get().getkey() : null;      assertnull(keyofthefirst); } 

thank in advance.

to return default value if there no match, use optional#orelse

names.entryset().stream()   .filter(e -> e.getvalue().equals("donkey"))   .map(map.entry::getkey)   .findfirst()   .orelse(null); 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -