|
1 | 1 | package com.jnape.palatable.lambda.lens.lenses; |
2 | 2 |
|
3 | 3 | import com.jnape.palatable.lambda.adt.Maybe; |
| 4 | +import com.jnape.palatable.lambda.adt.hlist.Tuple2; |
4 | 5 | import com.jnape.palatable.lambda.functions.builtin.fn2.Filter; |
5 | 6 | import com.jnape.palatable.lambda.lens.Lens; |
6 | 7 |
|
|
15 | 16 | import static com.jnape.palatable.lambda.functions.builtin.fn2.Eq.eq; |
16 | 17 | import static com.jnape.palatable.lambda.functions.builtin.fn2.Map.map; |
17 | 18 | import static com.jnape.palatable.lambda.functions.builtin.fn2.ToCollection.toCollection; |
| 19 | +import static com.jnape.palatable.lambda.functions.builtin.fn2.ToMap.toMap; |
18 | 20 | import static com.jnape.palatable.lambda.lens.Lens.lens; |
19 | 21 | import static com.jnape.palatable.lambda.lens.Lens.simpleLens; |
20 | 22 | import static com.jnape.palatable.lambda.lens.functions.View.view; |
21 | 23 | import static com.jnape.palatable.lambda.lens.lenses.MaybeLens.unLiftA; |
22 | | -import static java.util.stream.Collectors.toMap; |
23 | 24 | import static java.util.stream.Collectors.toSet; |
24 | 25 |
|
25 | 26 | /** |
@@ -137,16 +138,16 @@ public static <K, V> Lens.Simple<Map<K, V>, Map<V, K>> inverted() { |
137 | 138 | * @return a lens that focuses on a map while mapping its values |
138 | 139 | */ |
139 | 140 | public static <K, V, V2> Lens.Simple<Map<K, V>, Map<K, V2>> mappingValues(Function<? super V, ? extends V2> fn) { |
140 | | - return Lens.simpleLens(m -> m.entrySet().stream().collect(toMap(Map.Entry::getKey, kv -> fn.apply(kv.getValue()))), |
141 | | - (s, b) -> { |
142 | | - //todo: remove this madness upon arrival of either invertible functions or Iso<V,V2> |
143 | | - Set<K> retainKeys = Filter.<Map.Entry<K, V>>filter(kv -> eq(fn.apply(kv.getValue()), b.get(kv.getKey()))) |
144 | | - .andThen(map(Map.Entry::getKey)) |
145 | | - .andThen(toCollection(HashSet::new)) |
146 | | - .apply(s.entrySet()); |
147 | | - Map<K, V> copy = new HashMap<>(s); |
148 | | - copy.keySet().retainAll(retainKeys); |
149 | | - return copy; |
150 | | - }); |
| 141 | + return simpleLens(m -> toMap(HashMap::new, map(t -> t.biMapR(fn), map(Tuple2::fromEntry, m.entrySet()))), |
| 142 | + (s, b) -> { |
| 143 | + //todo: remove this madness upon arrival of either invertible functions or Iso<V,V2> |
| 144 | + Set<K> retainKeys = Filter.<Map.Entry<K, V>>filter(kv -> eq(fn.apply(kv.getValue()), b.get(kv.getKey()))) |
| 145 | + .andThen(map(Map.Entry::getKey)) |
| 146 | + .andThen(toCollection(HashSet::new)) |
| 147 | + .apply(s.entrySet()); |
| 148 | + Map<K, V> copy = new HashMap<>(s); |
| 149 | + copy.keySet().retainAll(retainKeys); |
| 150 | + return copy; |
| 151 | + }); |
151 | 152 | } |
152 | 153 | } |
0 commit comments