如何根据这些条件对对象的HashSet进行排序?

时间:2013-06-20 21:37:11

标签: java sorting comparison hashset treeset

我在这里把SSCCE扔到了一起:

House.java:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class House {

    private Status currentStatus;
    private String city;
    private Date date;

    public enum Status { AVAILABLE, 
                         SOLD, 
                         CONTINGENT 
    }

    public House(Status s, String c, String d) throws ParseException {
        currentStatus = s;
        city = c;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        date = sdf.parse(d);
    }
}

SortingTest.java:

import java.text.ParseException;
import java.util.HashSet;
import sortingtest.House.Status;    

public class SortingTest {


    public static void main(String[] args) throws ParseException {
        HashSet<House> houses = new HashSet<House>();
        houses.add(new House(Status.AVAILABLE, "New York City", "2007-11-11"));
        houses.add(new House(Status.SOLD, "Los Angeles", "2005-06-11"));
        houses.add(new House(Status.AVAILABLE, "Chicago", "2012-05-03"));
        houses.add(new House(Status.CONTINGENT, "Portland", "2007-10-11"));

        //Sort HashSet of House objects by criteria listed below      

        //sort by Status.AVAILABLE
            //call sort
            //System.out.println("Sorted by available");
            //iterate set and print out sorted houses

        //sort by Status.SOLD
            //call sort
            //System.out.println("Sorted by sold");
            //iterate set and print out sorted houses

        //sort by Status.CONTINGENT
            //call sort
            //System.out.println("Sorted by contingent");
            //iterate set and print out sorted houses

        //sort by City
            //call sort
            //System.out.println("Sorted alphabetically by City");
            //iterate set and print out sorted houses

        //sort by City
            //call sort
            //System.out.println("Sorted reverse alphabetically by City");
            //iterate set and print out sorted houses

        //sort by Date (newest)
            //call sort
            //System.out.println("Sorted by newest date (fewest days on market)");
            //iterate set and print out sorted houses

        //sort by Date (oldest)
            //call sort
            //System.out.println("Sorted oldest date (most days on market)");
            //iterate set and print out sorted houses
    }
}

所以最终我想要创建一个SetSorter类,我可以调用一个方法来返回以特定格式排序的Set。

如果您不想阅读代码中的注释,我想根据以下内容进行排序:

  • Status.AVAILABLE
  • Status.SOLD
  • Status.Contingent
  • 城市(按字母顺序排列)
  • 城市(按字母顺序反向)
  • 日期(市场上的最少日期)
  • 日期(大部分上市日期)

我已经对它进行了一些阅读,看起来人们建议将其放入TreeSet进行排序和使用比较器。我已经看过多个例子,人们要么为比较器创建一个单独的类,要么使指定的类实现可比较。

我没有看到的是有人写了一个额外的类来处理所有的排序。这可能吗?如果是这样,有人可以告诉我从哪里开始?这些似乎比典型的整数比较稍微复杂一些。

编辑以澄清

Status.AVAILABLE 排序时,我希望Set能够按以下方式显示对象:

  • Status.AVAILABLE(在顶部/第一个)
  • Status.CONTINGENT(在Status.AVAILABLE / second之后)
  • Status.SOLD(在Status.CONTINGENT / last之后)

Status.CONTINGENT 排序时,我希望该集按如下方式排序:

  • Status.CONTINGENT
  • Status.SOLD
  • Status.AVAILABLE

Status.SOLD 排序时,我希望按以下方式排序:

  • Status.SOLD
  • Status.CONTINGENT
  • Status.AVAILABLE

编辑#2终极目标

我想有一个类,我可以简单地调用方法来对集合进行排序。

即:

//sort by date
SetSorter.sortByData(treeSet);    //returns TreeSet sorted by date

//sort by city
SetSorter.sortByCity(treeSet);    //returns TreeSet sorted by City

//sort by other criteria 

编辑#3

class SortByCity implements Comparator<House> {
    @Override
    public int compare(House h1, House h2) {
        return h1.getCity().compareTo(h1.getCity());
    } 
}


houses = new TreeSet(new SortByCity());

我认为这是一种简单的方法,但这些都是小班,而且(在我看来)看起来很混乱。谁想在.java中有7个迷你课?

有人可以为我提供一些替代示例吗?

1 个答案:

答案 0 :(得分:1)

以下是一些有关排序的示例。我没有执行日期或反向字母排序(这是一项任务)。请注意有关将两个房屋比较为值0的内联评论!

public class HouseSorter {

    enum Status {
        SOLD, AVAILABLE, CONTINGENT;
    }

    /**
     * Immutable house (if a house is sold or not does not change a house, use a
     * Map instead).
     */
    private static class House {
        private final String city;

        House(String city) {
            this.city = city;
        }

        public String getCity() {
            return city;
        }

        @Override
        public String toString() {
            return "House in " + city;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (!House.class.isAssignableFrom(obj.getClass())) {
                return false;
            }
            return this.city.equalsIgnoreCase(((House) obj).city);
        }

        @Override
        public int hashCode() {
            return city.hashCode();
        }
    }

    public static SortedSet<House> sortAlphabetically(Set<House> houses) {
        TreeSet<House> sortedHouses = new TreeSet<House>(
                new Comparator<House>() {
                    @Override
                    public int compare(House o1, House o2) {
                        return o1.getCity().compareTo(o2.getCity());
                    }
                });
        sortedHouses.addAll(houses);
        return sortedHouses;
    }

    public static SortedSet<House> sortByStatus(
            final Map<House, Status> houseStatusMap) {
        TreeSet<House> sortedHouses = new TreeSet<House>(
                new Comparator<House>() {
                    @Override
                    public int compare(House o1, House o2) {
                        int compareByStatus = houseStatusMap.get(o1).compareTo(
                                houseStatusMap.get(o2));
                        if (compareByStatus != 0) {
                            return compareByStatus;
                        }
                        // you need an additional compare, until none of the
                        // houses compare with result 0
                        // otherwise the houses would be equal and therefore
                        // removed from the set
                        return o1.getCity().compareTo(o2.getCity());
                    }
                });
        sortedHouses.addAll(houseStatusMap.keySet());
        return sortedHouses;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        final Map<House, Status> houseStatusMap = new HashMap<House, Status>();
        House house0 = new House("Beverwijk");
        houseStatusMap.put(house0, Status.SOLD);
        House house1 = new House("Opmeer");
        houseStatusMap.put(house1, Status.SOLD);
        House house2 = new House("Amstelveen");
        houseStatusMap.put(house2, Status.AVAILABLE);
        House house3 = new House("Haarlem");
        houseStatusMap.put(house3, Status.CONTINGENT);

        System.out.println(sortAlphabetically(houseStatusMap.keySet()));
        System.out.println(sortByStatus(houseStatusMap));
    }
}