Java 在HashMap中将值从一个键移动到另一个键

Java 在HashMap中将值从一个键移动到另一个键,java,arraylist,hashmap,Java,Arraylist,Hashmap,我有一个ArrayList,它保存student对象,如下所示: List<Students> stdList = new ArrayList<Students>(); stdList.add(new Students(1,"std1","address1")); stdList.add(new Students(2,"std2","address2")); stdList.add(new Students(3,"std3","address3")); stdList.a

我有一个ArrayList,它保存student对象,如下所示:

List<Students> stdList = new ArrayList<Students>();
stdList.add(new Students(1,"std1","address1"));
stdList.add(new Students(2,"std2","address2"));
stdList.add(new Students(3,"std3","address3"));
stdList.add(new Students(4,"std4","address4"));
stdList.add(new Students(5,"std5","address5"));
stdList.add(new Students(6,"std6","address6"));
stdList.add(new Students(7,"std7","address7"));
stdList.add(new Students(8,"std8","address8"));
现在我需要将一个值从“键1”移动到“键2”,比如说“3 std3 address3”:

如何实现这一点?

List ls=hm.get(1);
List<Student> ls = hm.get(1);
Student st  = ls.get(3);
ls.remove(st); hm.get(2).add(st);
学生st=ls.get(3); ls.移除(st);hm.get(2).添加(st);
如果可以通过索引访问列表,则无需搜索列表。

假设“someKey”是要删除的键,然后

key1.put(someKey, key2.remove(someKey));

解决方案是从HashMap中获取学生列表,并删除要移动的学生对象。然后从HashMap中获取另一个列表,只需添加对象即可

我没有运行下面的代码,但应该是这样的

//Get the list for Key 1
List<Students> list = hm.get(Integer.valueOf(1));

//Remove the 3rd value, that would be your "3 std3 address3"
Students std = list.remove(2);

//Now get the list of Key 2
list = hm.get(Integer.valueOf(2));

//Add the value to that list
list.add(std);
//获取键1的列表
List List=hm.get(Integer.valueOf(1));
//删除第三个值,即“3 std3 address3”
学生标准=列表。删除(2);
//现在获取键2的列表
list=hm.get(Integer.valueOf(2));
//将值添加到该列表中
列表。添加(标准);
你可以这样做

 Student stud3=myMap.get(1).remove(myMap.get(1).get(2));
 List<Student> secondList=myMap.get(2);
 secondList.add(stud3);
 myMap.put(2,secondList);
学生stud3=myMap.get(1).remove(myMap.get(1.get(2)); List secondList=myMap.get(2); 添加第二个列表(stud3); myMap.put(2,第二个列表);
其中myMap是由您形成的映射。

我认为您知道如何在列表/映射中搜索元素,以及如何删除/添加它们。您已经在代码中显示了它。您的需求只是这些方法调用的另一个组合,它们对您来说不会是问题

我猜你不能再往前走了,因为你遇到了一个例外:

ConcurrentModificationException
因为我看到您使用了
subList()
方法。它将返回备份列表的视图。您可以更改该列表中的元素,但对结构的任何修改都会引发该异常

如果这是您面临的问题,简单的解决方案是在调用
subList
时创建一个新列表,如
newarraylist(stdList.subList(i,i+4))
,然后您可以进行结构修改

如果这不是你的问题,请留下评论,我会删除答案


另外,你可能想改变一下你的数据结构,我不知道你的确切要求,但目前的结构不太方便。。。。。您可以查看guava multi-map…

您想合并值还是覆盖?您是在询问大规模数据中的搜索算法,还是直接询问如何更改HashMap中的条目?删除(3)将删除第四个学生my bro:p
//Get the list for Key 1
List<Students> list = hm.get(Integer.valueOf(1));

//Remove the 3rd value, that would be your "3 std3 address3"
Students std = list.remove(2);

//Now get the list of Key 2
list = hm.get(Integer.valueOf(2));

//Add the value to that list
list.add(std);
 Student stud3=myMap.get(1).remove(myMap.get(1).get(2));
 List<Student> secondList=myMap.get(2);
 secondList.add(stud3);
 myMap.put(2,secondList);
ConcurrentModificationException