【问题标题】:How to implement isEmpty() for hashmap using stream?如何使用流为 hashmap 实现 isEmpty()?
【发布时间】:2019-03-29 20:49:10
【问题描述】:

我正在实现自己的 hashmap,尽可能使用流。 我想不出 isEmpty() 的正确语法。

我尝试了多种形式:

 return buckets.entrySet().stream().forEach(List::isEmpty());

下面是部分代码:

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>>());
         }
    }
}

我想写一个简单的流,比如:

return buckets.stream().mapToInt(List::size).sum();

对于 isEmpty()。

【问题讨论】:

    标签: java hashmap java-stream


    【解决方案1】:

    你可以用这个:

    public boolean isEmpty() {
        return buckets.stream().allMatch(List::isEmpty);
    }
    

    如果buckets 为空或所有子列表为空,则返回true

    【讨论】:

    • 谢谢你成功了,我会进一步研究 allMatch()。
    • 你也可以看看anyMatch()noneMatch()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2015-07-06
    相关资源
    最近更新 更多