2013-06-20 2 views
0

나는 SSCCE 여기에 함께 발생했습니다이러한 기준에 따라 개체의 HashSet을 어떻게 정렬합니까?

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 클래스 어디서 특정 형식으로 정렬 된 집합을 반환하는 메서드를 호출 할 수 있습니다. 당신이, 내가 꿔 코드의 의견을 읽고 싶지 않았다 경우

가에 따라 정렬 :

  • Status.AVAILABLE
  • Status.SOLD
  • Status.Contingent
  • 도시 (알파벳 순)
  • 도시 (알파벳 순 역)
  • 날짜 (시장에 적은 일)
  • 날짜 (시장에서 가장 일)

나는 그것을 읽는 조금 해봤 사람들이 정렬 및 비교기를 사용하기위한 TreeSet의로를 만드는 것이 좋습니다 것 같습니다. 필자는 사람들이 비교기 용으로 별도의 클래스를 만들거나 지정된 클래스를 비교 가능하게 구현하는 여러 예제를 보았습니다.

내가 보지 못한 것은 누군가가 모든 정렬을 처리하기 위해 여분의 클래스를 작성한다는 것입니다. 이것이 가능한가? 그렇다면 누군가 나를 시작할 곳을 보여줄 수 있습니까? 이것은 전형적인 정수 비교보다 약간 더 복잡한 비교처럼 보입니다. 설명에 대한

편집

Status.AVAILABLE에 의해 정렬 내가 설정은 개체가 좋아에 의해 나타납니다 : (첫번째/상단에)

  • Status.AVAILABLE
  • Status.CONTINGENT (Status.AVAILABLE/초 이후)
  • Status.SOLD (상태. 연결 완료 후/마지막)
  • Status.CONTINGENT
    에 의해 분류하면 다음과 같이

나는 분류 세트를 원하는 :

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

정렬 에 의해 상태.

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

편집 # 2 궁극적 인 목표 :

I를 다음과 같이 I 정렬 세트를 원하는 판매 집합을 정렬하는 메서드를 간단하게 호출 할 수있는 클래스를 갖고 싶습니다.

즉 :

//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 개의 미니 클래스가 있어야하는 사람은 누구입니까?

내가보기에 누군가 다른 예제를 제공 할 수 있습니까?

+0

'Status.AVAILABLE'을 기준으로 정렬하는 것은 무엇을 의미합니까? 그게 enum이야? –

+0

@RohitJain 모든 최상위에있는 모든 Status.AVAILABLE을 의미합니다. 나는 분명히하기 위해 나의 지위를 편집 할 것이다. – WilliamShatner

+0

'TreeSet'을 사용하고'Comparator '을 제공하십시오. –

답변

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)); 
    } 
} 
+0

예를 들어 주셔서 감사합니다. 내일은 테스트 할 시간이 없었습니다. 여러 가지 방법으로 비교하기 위해 상태가 필요합니까? 열거 형의 순서로 정렬하고 싶었지만 여전히지도를 비교해야할까요? 다시 말하지만, ** 훌륭한 ** 예를 들어 주셔서 감사합니다!또한 데이터 비교기 예제를 검색해 보겠습니다. – WilliamShatner

+0

아니요 객체 지향 디자인이 아닙니다. 나는 "근본적으로"말하기, 집의 상태가 집 그 자체의 일부가 아니라고 생각합니다. 문은 아마도 창문이지만 외부의 작은 사인은 아닙니다. –

+0

예제에 다시 한 번 감사드립니다. 이 컴파일러가 어떻게 작동하는지 이해하는 데 정말로 도움이되었습니다. 상태에 따라 정렬하는 데 약간의 문제가 있습니다. 코드에서 지적했듯이 추가 검사가 필요합니다. 서문으로 주문하고 싶다면 내 수 표는 어떻게 생겼을까요? – WilliamShatner

관련 문제