Java - 如何创建新条目(键、值)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3110547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:32:11  来源:igfitidea点击:

Java - How to create new Entry (key, value)

javadictionarycollectionskey-value

提问by Spiderman

I'd like to create new item that similarly to Util.Map.Entrythat will contain the structure key, value.

我想创建一个新的项目,与Util.Map.Entry该项目类似,将包含结构key, value

The problem is that I can't instantiate a Map.Entrybecause it's an interface.

问题是我无法实例化 aMap.Entry因为它是一个接口。

Does anyone know how to create a new generic key/value object for Map.Entry?

有谁知道如何为 Map.Entry 创建一个新的通用键/值对象?

采纳答案by Jesper

You can just implement the Map.Entry<K, V>interface yourself:

您可以Map.Entry<K, V>自己实现接口:

import java.util.Map;

final class MyEntry<K, V> implements Map.Entry<K, V> {
    private final K key;
    private V value;

    public MyEntry(K key, V value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public K getKey() {
        return key;
    }

    @Override
    public V getValue() {
        return value;
    }

    @Override
    public V setValue(V value) {
        V old = this.value;
        this.value = value;
        return old;
    }
}

And then use it:

然后使用它:

Map.Entry<String, Object> entry = new MyEntry<String, Object>("Hello", 123);
System.out.println(entry.getKey());
System.out.println(entry.getValue());

回答by polygenelubricants

There's public static class AbstractMap.SimpleEntry<K,V>. Don't let the Abstractpart of the name mislead you: it is in fact NOTan abstractclass (but its top-level AbstractMapis).

public static class AbstractMap.SimpleEntry<K,V>。不要让Abstract名称的一部分误导您:它实际上不是一个abstract类(但它的顶级AbstractMap是)。

The fact that it's a staticnested class means that you DON'Tneed an enclosing AbstractMapinstance to instantiate it, so something like this compiles fine:

这是一个事实static嵌套类意味着你不要需要一个封闭的AbstractMap情况下进行实例化,所以像这样的编译罚款:

Map.Entry<String,Integer> entry =
    new AbstractMap.SimpleEntry<String, Integer>("exmpleString", 42);

As noted in another answer, Guava also has a convenient staticfactory method Maps.immutableEntrythat you can use.

正如另一个答案中所述,番石榴还有一个方便的static工厂方法供Maps.immutableEntry您使用。



You said:

你说:

I can't use Map.Entryitself because apparently it's a read-only object that I can't instantiate new instanceof

我不能使用Map.Entry它自己,因为显然它是一个只读对象,我无法实例化 newinstanceof

That's not entirely accurate. The reason why you can't instantiate it directly (i.e. with new) is because it's an interface Map.Entry.

这并不完全准确。您不能直接(即使用new)实例化它的原因是因为它是一个interface Map.Entry.



Caveat and tip

警告和提示

As noted in the documentation, AbstractMap.SimpleEntryis @since 1.6, so if you're stuck to 5.0, then it's not available to you.

如文档中所述,AbstractMap.SimpleEntryis @since 1.6,因此如果您坚持使用 5.0,那么您将无法使用它。

To look for another known class that implements Map.Entry, you can in fact go directly to the javadoc. From the Java 6 version

要查找另一个已知类 that implements Map.Entry,您实际上可以直接转到 javadoc。从Java 6 版本开始

Interface Map.Entry

All Known Implementing Classes:

接口映射.Entry

所有已知的实现类

Unfortunately the 1.5 versiondoes not list any known implementing class that you can use, so you may have be stuck with implementing your own.

不幸的是,1.5 版本没有列出您可以使用的任何已知实现类,因此您可能一直在实现自己的类。

回答by finnw

Try Maps.immutableEntryfrom Guava

尝试来自Guava 的Maps.immutableEntry

This has the advantage of being compatible with Java 5 (unlike AbstractMap.SimpleEntrywhich requires Java 6.)

这具有与 Java 5 兼容的优点(与AbstractMap.SimpleEntry需要 Java 6不同。)

回答by Nels Beckman

I defined a generic Pair class that I use all the time. It's great. As a bonus, by defining a static factory method (Pair.create) I only have to write the type arguments half as often.

我定义了一个我一直使用的通用 Pair 类。这很棒。作为奖励,通过定义一个静态工厂方法 (Pair.create),我只需编写一半的类型参数。

public class Pair<A, B> {

    private A component1;
    private B component2;

    public Pair() {
            super();
    }

    public Pair(A component1, B component2) {
            this.component1 = component1;
            this.component2 = component2;
    }

    public A fst() {
            return component1;
    }

    public void setComponent1(A component1) {
            this.component1 = component1;
    }

    public B snd() {
            return component2;
    }

    public void setComponent2(B component2) {
            this.component2 = component2;
    }

    @Override
    public String toString() {
            return "<" + component1 + "," + component2 + ">";
    }

    @Override
    public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result
                            + ((component1 == null) ? 0 : component1.hashCode());
            result = prime * result
                            + ((component2 == null) ? 0 : component2.hashCode());
            return result;
    }

    @Override
    public boolean equals(Object obj) {
            if (this == obj)
                    return true;
            if (obj == null)
                    return false;
            if (getClass() != obj.getClass())
                    return false;
            final Pair<?, ?> other = (Pair<?, ?>) obj;
            if (component1 == null) {
                    if (other.component1 != null)
                            return false;
            } else if (!component1.equals(other.component1))
                    return false;
            if (component2 == null) {
                    if (other.component2 != null)
                            return false;
            } else if (!component2.equals(other.component2))
                    return false;
            return true;
    }

    public static <A, B> Pair<A, B> create(A component1, B component2) {
            return new Pair<A, B>(component1, component2);
    }

}

回答by parxier

org.apache.commons.lang3.tuple.Pairimplements java.util.Map.Entryand can also be used standalone.

org.apache.commons.lang3.tuple.Pair实现java.util.Map.Entry,也可以单独使用。

Also as others mentioned Guava's com.google.common.collect.Maps.immutableEntry(K, V)does the trick.

也正如其他人提到的com.google.common.collect.Maps.immutableEntry(K, V)那样,番石榴可以解决问题。

I prefer Pairfor its fluent Pair.of(L, R)syntax.

我更喜欢Pair它流畅的Pair.of(L, R)语法。

回答by tanghao

Why Map.Entry? I guess something like a key-value pair is fit for the case.

为什么Map.Entry?我想像键值对这样的东西适合这种情况。

Use java.util.AbstractMap.SimpleImmutableEntryor java.util.AbstractMap.SimpleEntry

使用java.util.AbstractMap.SimpleImmutableEntryjava.util.AbstractMap.SimpleEntry

回答by Eric Leschinski

Example of AbstractMap.SimpleEntry:

AbstractMap.SimpleEntry 的示例:

import java.util.Map; 
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;

Instantiate:

实例化:

ArrayList<Map.Entry<Integer, Integer>> arr = 
    new ArrayList<Map.Entry<Integer, Integer>>();

Add rows:

添加行:

arr.add(new AbstractMap.SimpleEntry(2, 3));
arr.add(new AbstractMap.SimpleEntry(20, 30));
arr.add(new AbstractMap.SimpleEntry(2, 4));

Fetch rows:

获取行:

System.out.println(arr.get(0).getKey());
System.out.println(arr.get(0).getValue());
System.out.println(arr.get(1).getKey());
System.out.println(arr.get(1).getValue());
System.out.println(arr.get(2).getKey());
System.out.println(arr.get(2).getValue());

Should print:

应该打印:

2
3
20
30
2
4

It's good for defining edges of graph structures. Like the ones between neurons in your head.

它适用于定义图结构的边。就像大脑中神经元之间的那些。

回答by Radon Rosborough

If you are using Clojure, you have another option:

如果您使用的是 Clojure,您还有另一种选择:

(defn map-entry
  [k v]
  (clojure.lang.MapEntry/create k v))

回答by Nicolas Filotto

Starting from Java 9,there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object).

Java 9开始有一个新的实用程序方法允许创建一个不可变的条目,即Map#entry(Object, Object).

Here is a simple example:

这是一个简单的例子:

Entry<String, String> entry = Map.entry("foo", "bar");

As it is immutable, calling setValuewill throw an UnsupportedOperationException. The other limitations are the fact that it is not serializable and nullas key or value is forbidden, if it is not acceptable for you, you will need to use AbstractMap.SimpleImmutableEntryor AbstractMap.SimpleEntryinstead.

由于它是不可变的,调用setValue将抛出一个UnsupportedOperationException. 其他限制是它不可序列化,并且null由于键或值是被禁止的,如果您不能接受,您将需要使用AbstractMap.SimpleImmutableEntryAbstractMap.SimpleEntry代替。

NB:If your need is to create directly a Mapwith 0 to up to 10 (key, value) pairs, you can instead use the methods of type Map.of(K key1, V value1, ...).

注意:如果您需要直接创建Map0 到最多 10 个(键,值)对,您可以改用 type 的方法Map.of(K key1, V value1, ...)

回答by Juan David Ortega Tapias

You could actually go with: Map.Entry<String, String> en= Maps.immutableEntry(key, value);

你实际上可以去: Map.Entry<String, String> en= Maps.immutableEntry(key, value);