Java 8 extracts the first key from the matching value in the map
•
Java
Suppose I have a map with a given name and last name pair, and I want to find the given name of the first entry in the map with a last name matching a certain value
In my test case example below, I propose two methods
However, the first one (looking for the given name of the first person named "dongkey") will throw Java util. NoSuchElementException: no value exists, so it is unsafe
The second job, but it's not only difficult to read, but it's a little less useful
I just want to know that someone here will suggest that I use stream () or foreach () or both to achieve this, which is simpler
@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 you first
Solution
If it does not match, the default value is returned. Use optional #orelse
names.entrySet().stream()
.filter(e -> e.getValue().equals("Donkey"))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
