Skip to content

Commit ce69370

Browse files
committed
Merge pull request functionaljava#110 from dobesv/to-mutable-map-comparator
Preserve ordering function when converting to a TreeMap
2 parents ea6952b + 7dd5bd8 commit ce69370

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

core/src/main/java/fj/Ord.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
import java.math.BigDecimal;
1414
import java.math.BigInteger;
15+
import java.util.Comparator;
1516

1617
import static fj.Function.curry;
1718

@@ -503,4 +504,14 @@ public static <A> Ord<A> hashEqualsOrd() {
503504
});
504505
}
505506

507+
class OrdComparator implements Comparator<A> {
508+
@Override
509+
public int compare(A o1, A o2) {
510+
return Ord.this.compare(o1, o2).toInt();
511+
}
512+
}
513+
514+
public Comparator<A> toComparator() {
515+
return new OrdComparator();
516+
}
506517
}

core/src/main/java/fj/data/TreeMap.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import fj.*;
44

5+
import java.util.Comparator;
56
import java.util.Iterator;
67
import java.util.Map;
78

@@ -172,7 +173,9 @@ public Iterator<P2<K, V>> iterator() {
172173
* @return A new mutable map isomorphic to this tree map.
173174
*/
174175
public Map<K, V> toMutableMap() {
175-
final Map<K, V> m = new java.util.TreeMap<K, V>();
176+
final F<K, P2<K, Option<V>>> fakePair = k -> P.p(k, Option.none());
177+
final Comparator<K> comparator = tree.ord().comap(fakePair).toComparator();
178+
final Map<K, V> m = new java.util.TreeMap<K, V>(comparator);
176179
for (final P2<K, V> e : this) {
177180
m.put(e._1(), e._2());
178181
}

core/src/test/java/fj/data/TreeMapTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
package fj.data;
22

3+
import java.util.Map;
4+
35
import fj.Equal;
46
import fj.Ord;
57
import fj.P3;
68
import fj.Show;
79
import fj.P;
10+
811
import org.junit.Test;
912

1013
import static fj.data.Option.some;
14+
import static org.junit.Assert.assertEquals;
1115
import static org.junit.Assert.assertTrue;
1216

1317
/**
@@ -74,4 +78,12 @@ public void splitLookup() {
7478
assertTrue(eq.eq(p3, P.p(leftMap, some(Integer.toString(pivot)), rightMap)));
7579
}
7680

81+
@Test
82+
public void toMutableMap() {
83+
int max = 5;
84+
List<List<Integer>> l = List.range(1, max + 1).map(n -> List.single(n));
85+
TreeMap<List<Integer>, String> m2 = TreeMap.treeMap(Ord.listOrd(Ord.intOrd), l.zip(l.map(i -> i.toString())));
86+
Map<List<Integer>, String> mm = m2.toMutableMap();
87+
assertEquals(m2.keys().reverse(), List.iterableList(mm.keySet()));
88+
}
7789
}

0 commit comments

Comments
 (0)