简体   繁体   中英

Map from property of entry to entry

I often see lists of objects in java holding beans whose objects are picked by inspecting an ID field, ie

List<BeanObj> list = …

BeanObj myObj = null;
for(BeanObj b : list)
    if(b.getId().equals(whatIAmLookingFor)){
        myObj = b;
        break;
    }

(The second variant of this is storing the objects in Hibernate and retrieve them by SQL.)

Using a Map interface would really be sensible here, but there are difficulties, ie

  • the key field may be changed (in general, or even concurrently)
  • the key may be non-trivial to reach (think of b.getRoot().getAttribute("id").equals(…)

Have there been approaches to address this in a more efficient way, like implementing a

SpecialMap<String, BeanObj>("id") // use String getId() on BeanObj

or even

SpecialMap<String, BeanObj>("getRoot().getAttribute({0})", "id")
                          // use String getAttribute("id") on result of getRoot()

with add() instead put() which makes use of the id getter function to build its internal map? Probably this map will require the mapped objects to implement some interface to allow the map being notified of updates on the id field.

Perhaps the map could also take care that changing the ID of an object to an ID of an existing object is either not possible or results in dropping the object that previously had that ID.

You can manage the functionnal aspect of adding element to your map by using guava utilities:

import com.google.common.base.Function;

public class SpecialMap<K, V> extends HashMap<K, V>{
    private Function<V, K> function;

    public SpecialMap(Function<V, K> function) {
        this.function = function;
    }

    public void add(V value) {
        K key = function.apply(value);
        this.put(key, value);
    }

    public static void main(String[] args) {
        SpecialMap<String, BeanObj> specialMap = new SpecialMap<String, BeanObj>(new Function<BeanObj, String>() {
            @Override
            public String apply(BeanObj arg) {
                return arg.getRoot().getAttribute("id");
            }
        });
        specialMap.add(new BeanObj());
    }
}

In this example, the function will map your bean type to a string key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM