首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在HashMap中将值从一个关键点移动到另一个关键点

在HashMap中将值从一个关键点移动到另一个关键点
EN

Stack Overflow用户
提问于 2013-10-31 20:34:53
回答 5查看 2.1K关注 0票数 1

我有一个保存学生对象的ArrayList,如下所示:

代码语言:javascript
复制
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"));

现在,我需要将stdList分成两组,在本例中包含相等的学生数,即4,并将它们添加到hashMap中,这是通过以下方法实现的:

代码语言:javascript
复制
 int j=0;
 HashMap<Integer,List<Students>> hm = new HashMap<>();
    for (int i = 0; i < stdList.size(); i = i + 4) 
  {
     j++;
     hm.put(j,stdList.subList(i, i + 4));

  }

哈希图现在包含键值对,如下所示:

代码语言:javascript
复制
{1=[1 std1 address1, 2 std2 address2, 3 std3 address3, 4 std4 address4], 2=[5 std5 address5, 6 std6 address6, 7 std7 address7, 8 std8 address8]}

现在我需要将一个值"3 std3 address3“从"key 1”移动到"key 2“,如下所示:

代码语言:javascript
复制
{1=[1 std1 address1, 2 std2 address2,  4 std4 address4], 2=[5 std5 address5, 6 std6 address6, 7 std7 address7, 8 std8 address8,3 std3 address3]}

我如何才能做到这一点?

EN

回答 5

Stack Overflow用户

发布于 2013-10-31 20:50:11

假设"someKey“是您要删除的密钥,那么

代码语言:javascript
复制
key1.put(someKey, key2.remove(someKey));
票数 2
EN

Stack Overflow用户

发布于 2013-10-31 20:49:36

代码语言:javascript
复制
List<Student> ls = hm.get(1);
Student st  = ls.get(3);
ls.remove(st); hm.get(2).add(st);

如果可以通过索引访问列表,则不需要搜索列表。

票数 0
EN

Stack Overflow用户

发布于 2013-10-31 20:50:53

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

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

代码语言:javascript
复制
//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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19706701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档