Skip to content

Commit 25eb247

Browse files
Added toList(), toStream(), toOption() and toArray() to HashMap
1 parent 316ab8b commit 25eb247

2 files changed

Lines changed: 33 additions & 9 deletions

File tree

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

100644100755
Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
package fj.data;
22

3+
import fj.Equal;
34
import fj.F;
4-
import static fj.P.p;
5-
65
import fj.Hash;
76
import fj.P2;
8-
import static fj.data.Option.fromNull;
9-
import fj.Equal;
107

118
import java.util.Collection;
129
import java.util.Iterator;
1310

11+
import static fj.P.p;
12+
import static fj.data.Option.fromNull;
13+
1414
/**
1515
* A mutable hash map providing O(1) lookup.
1616
*
@@ -243,16 +243,32 @@ public Option<V> getDelete(final K k) {
243243
return fromNull(m.remove(new Key<K>(k, e, h)));
244244
}
245245

246+
public List<P2<K, V>> toList() {
247+
return keys().map(new F<K, P2<K, V>>() {
248+
public P2<K, V> f(final K k) {
249+
return p(k, get(k).some());
250+
}
251+
});
252+
}
253+
246254
/**
247255
* Projects an immutable collection of this hash map.
248256
*
249257
* @return An immutable collection of this hash map.
250258
*/
251259
public Collection<P2<K, V>> toCollection() {
252-
return keys().map(new F<K, P2<K, V>>() {
253-
public P2<K, V> f(final K k) {
254-
return p(k, get(k).some());
255-
}
256-
}).toCollection();
260+
return toList().toCollection();
261+
}
262+
263+
public Stream<P2<K, V>> toStream() {
264+
return toList().toStream();
265+
}
266+
267+
public Option<P2<K, V>> toOption() {
268+
return toList().toOption();
269+
}
270+
271+
public Array<P2<K, V>> toArray() {
272+
return toList().toArray();
257273
}
258274
}

core/src/test/fj/data/CheckHashMap.scala

100644100755
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import ArbitraryHashMap._
66
import Equal.{intEqual, stringEqual, optionEqual}
77
import Hash.{intHash, stringHash}
88
import org.scalacheck.Properties
9+
import fj.Equal._
10+
import fj.data.Option._
911

1012
object CheckHashMap extends Properties("HashMap") {
1113
implicit val equalInt: Equal[Int] = intEqual comap ((x: Int) => (x: java.lang.Integer))
@@ -40,6 +42,12 @@ object CheckHashMap extends Properties("HashMap") {
4042
m.get(k).isNone
4143
})
4244

45+
property("toList") = forAll((m: HashMap[Int, String]) => {
46+
val list = m.toList
47+
list.length() == m.keys().length() && list.forall((entry: P2[Int, String]) =>
48+
optionEqual(stringEqual).eq(m.get(entry._1()), some(entry._2())).asInstanceOf[java.lang.Boolean])
49+
})
50+
4351
property("getDelete") = forAll((m: HashMap[Int, String], k: Int) => {
4452
val x = m.get(k)
4553
val y = m.getDelete(k)

0 commit comments

Comments
 (0)