有没有办法用 Java 中已经包含的值初始化 SortedMap<Integer, String>?

Is there a way to initialize a SortedMap<Integer, String> with values already included in Java?

我想做这样的事情

SortedMap<Integer, String> stuff = new TreeMap<Integer, String>({1:"a",2:"b"});

很像您在 python 中所做的,但是在 Java 中可能吗?还是调用 .put() 两次的唯一方法?

从 Java9 开始,你可以这样做:

SortedMap<Integer, String> stuff = new TreeMap<>(Map.of(1, "a", 2, "b"));

Java文档链接:

TreeMap(Map<? extends K, ? extends V> m)

Map<K, V> of(K k1, V v1, K k2, V v2)

有双括号初始化器:

Map stuff = new TreeMap<Integer, String>() {{
    put(1, "a");
    put(2, "b");
}};
System.out.println(stuff);

如果你愿意,你可以把这个写在一行中。

虽然,我不推荐这个。阅读 here.

在Java 8:

Stream.of(new SimpleEntry<>(1, "a"), new SimpleEntry<>(2, "b"))
    .collect(
        Collectors.toMap(
            Entry::getKey, Entry::getValue,
            (a, b) -> { throw new IllegalStateException(); },
            TreeMap::new);

(Yuk).

最多只适用于 10 个条目。如果要对10个以上的条目进行操作,则需要使用Map.ofEntries(Map.entry(k, v), Map.entry(k, v) ...),如下所示:

import static java.util.Map.entry;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        SortedMap<Integer, String> stuff = new TreeMap<>(
                Map.ofEntries(entry(1, "a"), entry(2, "b"), entry(3, "c"), entry(4, "d"), entry(5, "e"), entry(6, "f"),
                        entry(7, "g"), entry(8, "h"), entry(9, "i"), entry(10, "j"), entry(11, "k"), entry(12, "l")));
        System.out.println(stuff);
    }
}

输出:

{1=a, 2=b, 3=c, 4=d, 5=e, 6=f, 7=g, 8=h, 9=i, 10=j, 11=k, 12=l}

根据来自 Java-8 and Java-14SortedMap 的 Javadoc,以下内容成立。它读取 SortedMap :

The expected "standard" constructors for all sorted map implementations are:

  1. A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys.

  2. A constructor with a single argument of type Comparator, which creates an empty sorted map sorted according to the specified comparator.

  3. A constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument, sorted according to the keys' natural ordering.

  4. A constructor with a single argument of type SortedMap, which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map.

并且在 (3) 的基础上,您可以简单地初始化一个 SortedMap 实现,将另一个 Map 初始化包装为构造函数参数。此 Q&A 中有很多选项与此处的其他建议相匹配。