[英]How do I create a mutable List backed by Map
How can I return a List<E>
backed by Map<K, E>
if I have a method for mapping Map
values to keys valueToKeyMapper
?如果我有将
Map
值映射到键valueToKeyMapper
的方法,如何返回由Map<K, E>
List<E>
支持的List<E>
?
class Foo {
private Map<Integer, String> backedMap = new HashMap<Integer, String>();
public List<String> getList() {
// NEED TO RETURN LIST BACKED BY MAP
}
public String getById(Integer id) {
return backedMap.get(id);
}
private static Integer valueToKeyMapper(String value) {
// just as exampl. In reality value will be POJO with method like getId()
return value.hashCode();
}
}
The code should work like this (simple example):代码应该像这样工作(简单示例):
Foo foo = new Foo();
foo.getList().add("something");
String value = foo.getById("something".hashCode());
// I should see something
Notes:笔记:
List
should be mutable and changes must be propagated in underlying Map
List
应该是可变的,并且更改必须在底层Map
传播Foo
, because it's used in other projectsFoo
公共方法,因为它在其他项目中使用List
List
顺序getById
method should continue to work fast getById
方法应该继续快速工作try something like this :---尝试这样的事情:---
List<String> list = new ArrayList<>();
Set keys = backedMap.keySet();
for (Iterator i = keys.iterator(); i.hasNext(); ) {
Integer key = (Integer) i.next();
String value = (String) backedMap.get(key);
list.add(value);
}
//To print Values in ArrayList :--
for(String s : list) {
System.out.println("printing element -- " + s);
}
An attempt using this List
on github: ListBackedByMap.java尝试在 github 上使用此
List
: ListBackedByMap.java
It usesForwardingList to maintain internal copy of the list in the map.它使用ForwardingList来维护地图中列表的内部副本。
There are two issues with this impl I found:我发现这个 impl 有两个问题:
ConcurrentModificationException
on attempt to modify list in iterator.ConcurrentModificationException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.