Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions core/src/main/java/fj/Ord.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Comparator;

import static fj.Function.curry;

Expand Down Expand Up @@ -503,4 +504,14 @@ public static <A> Ord<A> hashEqualsOrd() {
});
}

class OrdComparator implements Comparator<A> {
@Override
public int compare(A o1, A o2) {
return Ord.this.compare(o1, o2).toInt();
}
}

public Comparator<A> toComparator() {
return new OrdComparator();
}
}
5 changes: 4 additions & 1 deletion core/src/main/java/fj/data/TreeMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import fj.*;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;

Expand Down Expand Up @@ -172,7 +173,9 @@ public Iterator<P2<K, V>> iterator() {
* @return A new mutable map isomorphic to this tree map.
*/
public Map<K, V> toMutableMap() {
final Map<K, V> m = new java.util.TreeMap<K, V>();
final F<K, P2<K, Option<V>>> fakePair = k -> P.p(k, Option.none());
final Comparator<K> comparator = tree.ord().comap(fakePair).toComparator();
final Map<K, V> m = new java.util.TreeMap<K, V>(comparator);
for (final P2<K, V> e : this) {
m.put(e._1(), e._2());
}
Expand Down
12 changes: 12 additions & 0 deletions core/src/test/java/fj/data/TreeMapTest.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package fj.data;

import java.util.Map;

import fj.Equal;
import fj.Ord;
import fj.P3;
import fj.Show;
import fj.P;

import org.junit.Test;

import static fj.data.Option.some;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

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

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