Reputation: 308
I have a tree map with a following key value pair combination
Map is declared as follows
Map<String, List<Bean>> outputMap = new TreeMap<String,List<Bean>>();
Corresponding code will be
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);
}
}
}
And finally the OutputMap needs to be inserted to courseMap
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]]
So Here i need to sort the outputMap based on courseDate?Kindly help on how the desired output can be achieved ?
Thanks in advance..
Upvotes: 0
Views: 111
Reputation: 2698
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);
}
}
}
Upvotes: 1