如何对哈希图列表进行排序
我有一个 HashMap
的 List
,如下所示,
ArrayList l = new ArrayList ();
HashMap m = new HashMap ();
m.add("site_code","AL");
m.add("site_name","Apple");
l.add(m);
m = new HashMap();
m.add("site_code","JL");
m.add("site_name","Cat");
l.add(m);
m = new HashMap();
m.add("site_code","PL");
m.add("site_name","Banana");
l.add(m)
我想根据 site_name
对 list
进行排序。所以最终它会被排序为。
Apple, Banana, Cat
我正在尝试这样的事情:
Collections.sort(l, new Comparator(){
public int compare(HashMap one, HashMap two) {
//what goes here?
}
});
I have a List
of HashMap
such as below
ArrayList l = new ArrayList ();
HashMap m = new HashMap ();
m.add("site_code","AL");
m.add("site_name","Apple");
l.add(m);
m = new HashMap();
m.add("site_code","JL");
m.add("site_name","Cat");
l.add(m);
m = new HashMap();
m.add("site_code","PL");
m.add("site_name","Banana");
l.add(m)
I'd like to sort the list
based on site_name
. So in the end it would be sorted as.
Apple, Banana, Cat
I was trying something like this:
Collections.sort(l, new Comparator(){
public int compare(HashMap one, HashMap two) {
//what goes here?
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你让你的集合通用,它最终会看起来像这样:
如果你因为被困在 1.4 或更早的平台上而无法使用泛型,那么你将不得不强制转换
get
到String
。(另外,作为风格问题,我更喜欢将变量声明为
List
和Map
而不是ArrayList
和HashMap< /代码>。但这与问题无关。)
If you make your collections generic, it will end up looking about like this:
If you can't use generics because you're stuck on a 1.4 or earlier platform, then you'll have to cast the
get
's toString
.(Also, as a matter of style, I'd prefer declaring the variables as
List
andMap
rather thanArrayList
andHashMap
. But that's not relevant to the question.)我认为现在是考虑重新设计的好时机。从您的示例来看,您的所有对象似乎都具有相同的两个字段 -
site_name
和site_code
。在这种情况下,为什么不定义自己的类而不是使用 HashMap 呢?然后您可以使用
Collections.sort()
。I think this is a great time to think about a redesign. From your example, it looks like all of your objects have the same two fields -
site_name
andsite_code
. In that case, why not define your own class rather than using aHashMap
?And then you can just use
Collections.sort()
.比如:
我还没有编译或测试过这个,但它应该遵循这些思路。
Something like:
I haven't compiled or tested this, but it should be along these lines.