用Java对地图排序 [英] Sorting a map in java
本文介绍了用Java对地图排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有以下键值对组合的树形图
I have a tree map with a following key value pair combination
地图声明如下
Map<String, List<Bean>> outputMap = new TreeMap<String,List<Bean>>();
对应的代码将是
for (String course_date : shiftSet) {
Bean courseBean = null;
boolean valueExists = false;
for (Entry<String, List<Bean>> entry: courseMap.entrySet()){
valueExists = false;
String studentDetail = entry.getKey();
String [] studentSet = StringUtils.getArray(studentDetail , ",");
String studentId = studentSet[0];
String courseId = studentSet[1];
for(Bean resultBean : entry.getValue()){
if(course_date.equalsIgnoreCase(resultBean.getCourseDate()){
valueExists = true;
}
}
if(!valueExists ) {
courseBean = new Bean();
courseBean.setStudent(studentId);
courseBean.setCourse(courseId);
List<Bean> courseList = entry.getValue();
courseList.add(courseBean);
outputMap.put(studentId+courseId, courseList);
}
}
}
最后,需要将OutputMap插入到courseMap
And finally the OutputMap needs to be inserted to courseMap
OutputMap结果将为
OutputMap result will be
{ADV001,STU02=
[Bean[course_id=ADV1, student_id=STU1_2,Day=Wed-Night,courseDate=12-Feb-2014],
Bean[course_id=ADV1, student_id=STU1_2,Day=Tue-Day,courseDate=11-Feb-2014],
Bean[course_id=ADV1, student_id=STU1_2,Day=Tue-Night,courseDate=11-Feb-2014],
Bean[course_id=ADV1, student_id=STU1_2,Day=Wed-Day,courseDate=12-Feb-2014]]
所以在这里我需要根据courseDate对outputMap进行排序?请问如何才能实现所需的输出?
So Here i need to sort the outputMap based on courseDate?Kindly help on how the desired output can be achieved ?
先谢谢了.
推荐答案
TreeMap通过元素的键对元素进行排序,如果courseDate是值的一部分,则必须使用TreeSet,例如
A TreeMap sorts the elements by their key, if courseDate is part of the values, you'd have to use a TreeSet, e.g.
import java.util.Set;
import java.util.TreeSet;
public class Example {
public static void main(String[] args) {
Set<Dummy> example = new TreeSet<>();
example.add( new Dummy(7, "first dummy"));
example.add( new Dummy(2, "second dummy"));
example.add( new Dummy(3, "third dummy"));
System.out.println(example);
}
static class Dummy implements Comparable<Dummy>{
int courseDate;
String name;
Dummy(int courseDate, String name) {
this.courseDate = courseDate;
this.name = name;
}
@Override
public String toString() {
return String.format("[Dummy courseDate=%s, name=%s]", courseDate, name);
}
@Override
public int compareTo(Dummy o) {
// here you specify how the TreeSet will order your elements
return Integer.compare(this.courseDate, o.courseDate);
}
}
}
这篇关于用Java对地图排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文