Question

I try to create a PriorityQueue with dates. And I must to add something into this queue. Question is how to organise this priority queue? And how can I sort it by date?

To organise a queue i use this:

FileInputStream fis = new FileInputStream("calendar.ics");
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = builder.build(fis);

ComponentList listEvent = calendar.getComponents(Component.VEVENT);

PriorityQueue plan = new PriorityQueue();
for (Object elem : listEvent) {
    VEvent event = (VEvent) elem;
    plan.add(event.getStartDate());
}

I know I know that I should use a comparator, but but do not know how.

How do I write a comparator for the code above?

Was it helpful?

Solution

If you use iCal4j, you can create your plan object to sort your events as following:

PriorityQueue<VEvent> plan = new PriorityQueue<VEvent>(10, new Comparator<VEvent>() {    
    @Override
    public int compare(VEvent e1, VEvent e2)
    {
        Date d1 = e1.getStartDate().getDate();
        Date d2 = e2.getStartDate().getDate();
        return d1.compareTo(d2);
    }
});

OTHER TIPS

You need to provide a Comparator while creating a PriorityQueue in which the compare method should take two Date Objects and use the Date's natural ordering for Comparison.

You can also use natural ordering if your VEvent class can implement the Comparable interface

PriorityQueue<DtStart> plan = new PriorityQueue<DtStart>(10,new Comparator<DtStart>(){    
@Overide
public int compare(DtStart d1,DtStart d2)
{
//your logic goes here for comparing two DtStart  Objects
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top