通过所有对象包含的String值对Set内的对象进行排序 [英] Sorting objects within a Set by a String value that all objects contain

查看:95
本文介绍了通过所有对象包含的String值对Set内的对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是一个棘手的问题。我有一个集合列表。我想按顺序对集合中的对象进行排序。

Ok this is a tricky one. I have a list of Sets. I would like to sort the objects in the Sets in an order.

想象一下,每个集合都代表学校中的一个类。每个集合包含人物对象。 person对象包含name的String值。在我循环并将它们写出来之前,我想按名称安排人员名字。

Imagine each set as repressenting a class in a school. Each set contains person objects. A person object holds a String value for name. I'd like to arrange the Persons in the Set by name before I loop through and write them out.

是否有任何人使用收藏。 sort(); 或类似的东西来实现这个目标?

Is there anywahy to use Collections.sort(); or something similar to achieve this?

for (Set<Person> s : listOfAllChildren) {       
      for (Person p : s) {
        if(p.getClass().equalsIgnoreCase("Jones")){
          System.out.println(p.getName());
          }
         else if...//carry on through other classes 
        }                              
      }        

我知道一个班级中有2个以上的孩子可能会有相同的名字,但请忽略这个

推荐答案

设置没有订购的概念,因为它是一个集合。

A Set has no notion of ordering because, well, it's a set.

您可以使用 TreeSet 类实现的 SortedSet 接口。只需向构造函数提供一个合适的 Comparator ,或让你的 Person 类实现 Comparable

There is a SortedSet interface implemented by TreeSet class that you can use. Simply provide an appropriate Comparator to the constructor, or let your Person class implements Comparable.

这篇关于通过所有对象包含的String值对Set内的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆