Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values from HashMap as reference

Is it possible to get list of values from HashMap as a reference

class MyCustomObject {
    String name;
    Integer id;

    MyCustomObject(String name, Integer id){
        this.name = name;
        this.id = id;
    }
}
HashMap<Integer, MyCustomObject> map = new LinkedHashMap<>();
map.put (1, new MyCustomObject("abc",1));
map.put (2, new MyCustomObject("xyz",2));

List<MyCustomObject> list = new ArrayList<>(map.values());

Log.i(TAG,"************ List from HashMap ************");
for (MyCustomObject s : list) {
     Log.i(TAG,"name = "+s.name);
}

list.set(0,new MyCustomObject("temp",3));

Log.i(TAG,"************ List from HashMap after update ************");
for (MyCustomObject s : list) {
      Log.i(TAG,"name = "+s.name);
}

Log.i(TAG,"************ List from HashMap ************");

List<MyCustomObject> list2 = new ArrayList<>(map.values());
for (MyCustomObject s : list2) {
     Log.i(TAG,"name = "+s.name);
}

Output

**************** List from HashMap ***************
name = abc
name = xyz
**************** List from HashMap after update ***************
name = temp
name = xyz
**************** List from HashMap ***************
name = abc
name = xyz

Here if get list of values from HashMap it return deep-copy.

Update

My Requirement

  1. I want list of values from HashMap because I want to access items using their position
  2. I want to preserve order of values
  3. If I modify anything in the extracted list then it should reflect in HashMap too

Please do tell, if any third party library provide such data structure, or what would be best approach to handle this situation


2 Answers

You are creating an new List based on the values of the Map :

List<MyCustomObject> list = new ArrayList<>(map.values());

That's what creates the copy of the values Collection, and changes in that List cannot be reflected in the original Map.

If you modify the Collection returned by map.values() directly (for example, map.values().remove(new MyCustomObject("abc",1))), it will be reflected in the contents of the original Map. You wouldn't be able to call set on the Collection, though, since Collection doesn't have that method.

like image 110
Eran Avatar answered Jul 01 '26 23:07

Eran


Collection values()

Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

So use a Collection and assign values() to it. Or the entrySet().

like image 32
Joop Eggen Avatar answered Jul 01 '26 23:07

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!