繁体   English   中英

排序完整的HashMap

[英]Sorting a complete HashMap

我正在尝试使用看似复杂的HashMap对象来在android中化我的可扩展Listview。

我的HashMap的通用参数如下所示:

//HashMap<Map<YEAR,MONTH>,List<DAYS>>
HashMap<Map<Integer,Integer>,List<Integer>

我正在使用哈希图监视事件发生的日期,月份和年份。 因此,假设在2013年5月12日,20日和25日发生了一次活动,我将采取以下措施:

HashMap<Integer,Integer>,List<Integer>> events = new     HashMap<Integer,Integer>,List<Integer>();

HashMap<Integer,Integer> yearMonth = new HashMap<Integer,Integer>();
yearMonth.put(2013,5);
events.put(yearMonth,Arrays.asList(new Integer[]{12,20,25}));

我已经为我的可扩展列表视图创建了一个适配器,并且显示效果很好,如下所示。 现在,我希望能够对上述HashMap进行排序,首先按Year和Month排序,以便我的列表视图将按顶部顺序显示2014年的事件,然后依次显示2013年,2012年的事件。

这可能吗?

谢谢。

在此处输入图片说明

好吧,我刚刚读过“对hasmap进行排序”。 如果您真的想对数据进行排序,那么哈希表肯定是错误的。

也许您应该考虑使用链表...

创建您自己的类而不是哈希图,并调整适配器以适合那些对象。

然后,您可以通过实现Comparable并在类中创建compareTo()方法来实现自己的排序。

这为您提供了所需的所有控制。 例如:

public class myEvent implements Serializable, Comparable<myEvent>
{
  private Integer day;
  private Integer month;
  private Integer year;

  public myEvent( Integer day, Integer month, Integer year, <your other data> )
  {
     // Save the stuff here
     this.day = day; 
     this.month = month; 
     this.year = year; 
  }

  // Create getDay(), getMonth(), getYear() methods for each parameter

  public int compareTo( myEvent another )
  {
     // Here, compare the two events year by year, month by month, and day by day
     if ( this.year.compareTo( another.getYear() ) == 0 )
     {
         if ( this.month.compareTo( another.getMonth() ) == 0 )
         {
             return this.day.compareTo( another.getDay() );
         } else {
             return this.month.compareTo( another.getMonth() );
         }
     } else {
         return this.year.compareTo( another.getYear() );
     }
  }

}

编辑:当您想要对这些myEvent对象的列表进行排序时,可以使用Collection api来利用Comparable实现:

List<myEvent> allevents = new ArrayList<myEvent>();
// Add to the list
...
// Now sort it. 
Collections.sort( allevents );

祝好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM