oded ivry :
I'm implementing my own hashmap, using stream as much as possible. I can't figure out the right syntax for isEmpty().
I've tried many forms of:
return buckets.entrySet().stream().forEach(List::isEmpty());
Here is part of the code:
public class HashMap<K, V> implements Map<K, V> {
private static final int DEFAULT_CAPACITY = 64;
private List<List<Entry<K, V>>> buckets;
private int modCount = 0;
private KeySet keySet;
private EntrySet entrySet;
private ValuesCollection valColl;
//CTOR
public HashMap() {
buckets = new ArrayList<>(DEFAULT_CAPACITY);
for (int i = 0; i < DEFAULT_CAPACITY; ++i) {
buckets.add(i, new LinkedList<Entry<K, V>>());
}
}
}
I'd like to write a simple stream like:
return buckets.stream().mapToInt(List::size).sum();
for isEmpty().
Samuel Philipp :
You can use this:
public boolean isEmpty() {
return buckets.stream().allMatch(List::isEmpty);
}
This returns true
if buckets
is empty or all sublists are empty.