Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java equivalent of Python's defaultdict?

In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,

from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} 

Is there an equivalent to this in Java?

like image 351
gatoatigrado Avatar asked Nov 23 '09 21:11

gatoatigrado


People also ask

What is the difference between dict and Defaultdict?

The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key . In order to provide this functionality, the Python defaultdict type does two things: It overrides .

What is Python Defaultdict?

Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exists.

Does Defaultdict work in Python?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.


1 Answers

There is nothing that gives the behaviour of default dict out of the box. However creating your own default dict in Java would not be that difficult.

import java.util.ArrayList; import java.util.HashMap; import java.util.List;  public class DefaultDict<K, V> extends HashMap<K, V> {      Class<V> klass;     public DefaultDict(Class klass) {         this.klass = klass;         }      @Override     public V get(Object key) {         V returnValue = super.get(key);         if (returnValue == null) {             try {                 returnValue = klass.newInstance();             } catch (Exception e) {                 throw new RuntimeException(e);             }             this.put((K) key, returnValue);         }         return returnValue;     }     } 

This class could be used like below:

public static void main(String[] args) {     DefaultDict<Integer, List<Integer>> dict =         new DefaultDict<Integer, List<Integer>>(ArrayList.class);     dict.get(1).add(2);     dict.get(1).add(3);     System.out.println(dict); } 

This code would print: {1=[2, 3]}

like image 117
Tendayi Mawushe Avatar answered Sep 20 '22 17:09

Tendayi Mawushe