Guava: Set + Function = Map?

前端 未结 6 1135
眼角桃花
眼角桃花 2021-02-05 01:40

Is there an idiomatic way to take a Set and a Function, and get a Map live view? (i.e. the Map

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 02:23

    Caution. Sean Patrick Floyd's answer, although very useful, has a flaw. A simple one, but took me a while to debug so don't fall in the same trap: the MapEntry class requires equals and hashcode implementations. Here are mine (simple copy from the javadoc).

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Entry)) {
            return false;
        }
        Entry e2 = (Entry) obj;
        return (getKey() == null ? e2.getKey() == null : getKey().equals(e2.getKey()))
            && (getValue() == null ? e2.getValue() == null : getValue().equals(e2.getValue()));
    }
    
    @Override
    public int hashCode() {
        return (getKey() == null ? 0 : getKey().hashCode()) ^
            (getValue() == null ? 0 : getValue().hashCode());
    }
    

    This reply would be better as a commentary to the relevant answer, but AFAIU I don't have the right to post a comment (or did't find how to!).

提交回复
热议问题