Java 9
を使用して各エントリを作成できますMap.ofEntries
。Map.entry( k , v )
import static java.util.Map.entry;
private static final Map<Integer,String> map = Map.ofEntries(
entry(1, "one"),
entry(2, "two"),
entry(3, "three"),
entry(4, "four"),
entry(5, "five"),
entry(6, "six"),
entry(7, "seven"),
entry(8, "eight"),
entry(9, "nine"),
entry(10, "ten"));
ここMap.of
で彼の回答で Tagir が提案したように使用することもできますが、 を使用して 10 個を超えるエントリを作成することはできません。Map.of
Java 8
マップ エントリのストリームを作成できます。SimpleEntryとSimpleImmutableEntryの 2 つの実装が既にEntry
ありjava.util.AbstractMap
ます。この例では、前者を次のように利用できます。
import java.util.AbstractMap.*;
private static final Map<Integer, String> myMap = Stream.of(
new SimpleEntry<>(1, "one"),
new SimpleEntry<>(2, "two"),
new SimpleEntry<>(3, "three"),
new SimpleEntry<>(4, "four"),
new SimpleEntry<>(5, "five"),
new SimpleEntry<>(6, "six"),
new SimpleEntry<>(7, "seven"),
new SimpleEntry<>(8, "eight"),
new SimpleEntry<>(9, "nine"),
new SimpleEntry<>(10, "ten"))
.collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));