How to make a CaseInsensitiveConcurrentMap?

倾然丶 夕夏残阳落幕 提交于 2021-02-04 17:14:47

问题


How can I implement

class CaseInsensitiveConcurrentMap<V> implements ConcurrentMap<String , V>

which works just like ConcurrentHashMap<String , V> except that the keys are compared case-insensitively? The keys should not be converted to lowercase or uppercase.

Note that Collections.synchronizedMap(new TreeMap<String, new MyCaseInsensitiveComparator()) is no solution as it allows no concurrency and misses the additional methods.

Creating a String-like class with case-insensitive equals and hashCode is no option either, since the map has to be passed to methods expecting strings as keys.


回答1:


Have you tried

ConcurrentMap<String, Object> map = 
    new ConcurrentSkipListMap<String, Object>(
        String.CASE_INSENSITIVE_ORDER);



回答2:


If you really insist on all your constraints (ConcurrentHashMap) and String keys:

Overwrite any ConcurrentHashMap method and convert any key with key = key.toLowerCase().

Looks like a lot of work, and a lot of unit testing, so if I were you I would try to discuss the interface.

Example:

@Overwrite
public void V get(String key) {
  return super.get(transform(key));
}

// Extracted that to avoid cluttering your whole code with that specific transformation
// So you can easily change it
private String transform(String key) {
  return key.toLowerCase();
}

Ugly, but, given your constraints, feasible.



来源:https://stackoverflow.com/questions/6956940/how-to-make-a-caseinsensitiveconcurrentmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!