如何在Java中更改hashmap中列表中值的位置

时间:2012-04-19 13:02:16

标签: java arraylist hashmap

很抱歉提出另一个非常明显的问题 - 我正在努力使用哈希映射..

我想要做的是更改存储在hashmap中的列表中存储值的顺序,我不想使用迭代器。

例如,学校有一个课程列表,每个课程都有一个学生列表。在那里,大厅监控工作是随机挑选的课程列表中的第一个学生。选择课程后,列表顶部的学生将被列入其列出的所有课程的列表底部。有9门课程,学生可以出现在多个学生名单上。

我正在尝试做一些事情:

//instance variable
private HashMap<String, String[]> qualifiedStudents;
    qualifiedStudents = new HashMap<String, List<String>>();

  public void putStudentLastInRosters(String studentName)
  {
   for(String course : qualifiedStudents.keySet())
   {
      if(qualifiedStudents.get(course).contains(studentName)) 
    {
       qualifiedStudents.remove(course, studentName); 
       qualifiedStudents.put(course, studentName);
    }
  }

  }

6 个答案:

答案 0 :(得分:1)

试试这个:

//instance variable
private HashMap<String, List[]> qualifiedStudents;
    qualifiedStudents = new HashMap<String, List<String>>();

public String putStudentLastInRosters(String studentName) {
    for(String course : qualifiedStudents.keySet()) {
        List<String> students = qualifiedStudents.get(course);
        if(students.remove(studentName)) {
            students.add(studentName);
        }
    }
}

答案 1 :(得分:1)

您需要修改列表,而不是地图。所以代码应该是:

for (List<String> list : qualifiedStudents.values()) {
    if (list.remove(studentName)) {
        list.add(studentName);
    }
}

答案 2 :(得分:0)

考虑SortedMap执行此任务。

实现您自己的比较器以反映您要使用的排序顺序。

答案 3 :(得分:0)

如果我理解正确,您只想在每个课程的每个列表中重新排序学生。

    for(List<String> studentsInCourse : qualifiedStudents.values()) {
        if (studentsInCourse.remove(studentName)) {
            studentsInCourse.add(0, studentName);
        }
    }

答案 4 :(得分:0)

现在,当HashMap的值类型为String数组时,您似乎正在尝试从/向HashMap中删除并放置String对象。

你在哪里:

   qualifiedStudents.remove(course, studentName); 
   qualifiedStudents.put(course, studentName);

你想要获得对String数组的引用(我相信“course”)并在其中移动studentName字符串。就像barsju所说,使用ArrayList可能比使用String数组更容易。

答案 5 :(得分:0)

以下内容将返回班级中学生的ArrayList,并允许您执行删除和添加操作。我们只需删除studentsName,然后阅读即可。在链表中,这会将它添加到ArrayList的末尾。

qualifiedStudents.get(course)

我重新声明了你的HashMap。

    //instance variable
private HashMap<String, ArrayList<String>> qualifiedStudents = new HashMap<String, ArrayList<String>>();

  public void putStudentLastInRosters(String studentName)
  {
   for(String course : qualifiedStudents.keySet())
   {
      if(qualifiedStudents.get(course).contains(studentName)) 
    {
       qualifiedStudents.get(course).remove(studentName); 
       qualifiedStudents.get(course).add(studentName);
    }
  }

  }
相关问题