我有一个保存学生对象的ArrayList,如下所示:
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中,这是通过以下方法实现的:
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));
}哈希图现在包含键值对,如下所示:
{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“,如下所示:
{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]}我如何才能做到这一点?
发布于 2013-10-31 20:50:11
假设"someKey“是您要删除的密钥,那么
key1.put(someKey, key2.remove(someKey));发布于 2013-10-31 20:49:36
List<Student> ls = hm.get(1);
Student st = ls.get(3);
ls.remove(st); hm.get(2).add(st);如果可以通过索引访问列表,则不需要搜索列表。
发布于 2013-10-31 20:50:53
解决方案是从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);https://stackoverflow.com/questions/19706701
复制相似问题