简体   繁体   English

如何创建由 Map 支持的可变列表

[英]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传播
  • I can't modify public methods of object Foo , because it's used in other projects我不能修改对象Foo公共方法,因为它在其他项目中使用
  • I don't care about order in List我不在乎List顺序
  • The 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 上使用此ListListBackedByMap.java

It usesForwardingList to maintain internal copy of the list in the map.它使用ForwardingList来维护地图中列表的内部副本。

There are two issues with this impl I found:我发现这个 impl 有两个问题:

  1. It maintains additional copy of elements in memory它在内存中维护额外的元素副本
  2. It doesn't throws ConcurrentModificationException on attempt to modify list in iterator.它不会在尝试修改迭代器中的列表时引发ConcurrentModificationException

Tests avaliable here .在此处进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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