過去、何度も書いているかもしれない「マップの値からキーの参照」という命題
結果をStream で取得することにして、、、
public static <K , V> Stream<K> getKeysWithValue(Map<K, V> map, V v){ return map.entrySet().stream() .filter(e->v.equals(e.getValue())).map(Map.Entry::getKey); }
呼出し、、、
getKeysWithValue(map, "A").forEach(System.out::println);
equalsメソッドが使用できないなら、、
public static <K , V> Stream<K> getKeysWithCondition(Map<K, V> map, V v, BiPredicate<V, V> p){ return map.entrySet().stream() .filter(e->p.test(v, e.getValue())).map(Map.Entry::getKey); }
BiPredicate の第1引数=メソッドで指定するV
BiPredicate の第2引数=マップから取得したV
BiPredicateではなくて、Predicate で、、
public static <K , V> Stream<K> getKeysWithCondition(Map<K, V> map, Predicate<V> p){ return map.entrySet().stream() .filter(e->p.test(e.getValue())).map(Map.Entry::getKey); }
getKeysWithCondition(map, v->"A".equals(v)).forEach(System.out::println);
でも、こうなると、わざわざ、メソッドとして定義する必要なんて無いんじゃないか?
と思ってしまう。
でも、最初の
public static <K , V> Stream<K> getKeysWithValue(Map<K, V> map, V v){ return map.entrySet().stream() .filter(e->v.equals(e.getValue())).map(Map.Entry::getKey); }
は、結構良いかなあ??