Phoenix
Phoenix

Reputation: 8923

hashmap initialization with preexisting values?

If i have an int[] array = {1, 2, 3} and I want to initialise the hashmap with values below, is there a better way to do it ?

Map<Integer,Boolean> map = new HashMap<Integer,Boolean>();
            map.put(1,false);
            map.put(2,false);
            map.put(3,false);

Upvotes: 1

Views: 1855

Answers (3)

Steven Schlansker
Steven Schlansker

Reputation: 38526

If you use Guava,

ImmutableMap.of(1, false, 2, false, 3, false);

or,

ImmutableMap.builder().put(1, false).put(2, false).put(3, false).build()

Upvotes: 2

kosa
kosa

Reputation: 66637

Another way to initialize is:

Map<Integer,Boolean> map =  new HashMap<Integer, Boolean>() {
                            {
                                put(1,false);
                                put(2,false);
                                put(3,false);
                            }

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361595

for (int i: array) {
    map.put(i, false);
}

Upvotes: 7

Related Questions