2012-10-05 3 views
0

를 재정렬하는 방법 :목록 나는 다음과 같은 방법을 만들었습니다 <String>

public List<String> listAll() { 
    List worldCountriesByLocal = new ArrayList(); 

    for (Locale locale : Locale.getAvailableLocales()) { 
     final String isoCountry = locale.getDisplayCountry(); 
     if (isoCountry.length() > 0) { 
      worldCountriesByLocal.add(isoCountry); 
      Collections.sort(worldCountriesByLocal); 
     } 
    } 
    return worldCountriesByLocal; 
} 

그것의 아주 간단하고 로케일 사용자의 세계 국가의 목록을 반환합니다. 그런 다음 알파벳순으로 정렬합니다. 이 모든 것은 완벽하게 작동합니다 (나는 때때로 국가의 중복을 얻는 것 같습니다!).

어쨌든 내가 필요로하는 것은 미국과 영국을 상관없이 목록 상단에 배치하는 것입니다. 내가 가진 문제는 로케일에만 한정되어 있기 때문에 미국이나 영국에서 반환 할 색인이나 문자열을 분리 할 수 ​​없다는 것입니다.

모든 아이디어는 정말 감사하겠습니다.

+0

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Locale.html#getCountry() – MikeTheLiar

답변

1

중복을 제거하기 위해 TreeSet을 사용하고 Comparator을 사용하여 미국과 영국을 처음 시작할 수 있습니다.

국가별로 로캘이 두 개인 경우가 많아 중복되는 경우가 발생합니다. 미국 (스페인어)과 미국 (영어)이 있으며 세 개의 Switzerlands (프랑스어, 독일어 및 이탈리아어)가 있습니다.

public class AllLocales { 
    // Which Locales get priority. 
    private static final Locale[] priorityLocales = { 
    Locale.US, 
    Locale.UK 
    }; 

    private static class MyLocale implements Comparable<MyLocale> { 
    // My Locale. 
    private final Locale me; 

    public MyLocale(Locale me) { 
     this.me = me; 
    } 

    // Convenience 
    public String getCountry() { 
     return me.getCountry(); 
    } 

    @Override 
    public int compareTo(MyLocale it) { 
     // No duplicates in the country field. 
     if (getCountry().equals(it.getCountry())) { 
     return 0; 
     } 
     // Check for priority ones. 
     for (int i = 0; i < priorityLocales.length; i++) { 
     Locale priority = priorityLocales[i]; 
     // I am a priority one. 
     if (getCountry().equals(priority.getCountry())) { 
      // I come first. 
      return -1; 
     } 
     // It is a priority one. 
     if (it.getCountry().equals(priority.getCountry())) { 
      // It comes first. 
      return 1; 
     } 
     } 
     // Default to straight comparison. 
     return getCountry().compareTo(it.getCountry()); 
    } 
    } 

    public static List<String> listAll() { 
    Set<MyLocale> byLocale = new TreeSet(); 
    // Gather them all up. 
    for (Locale locale : Locale.getAvailableLocales()) { 
     final String isoCountry = locale.getDisplayCountry(); 
     if (isoCountry.length() > 0) { 
     //System.out.println(locale.getCountry() + ":" + isoCountry + ":" + locale.getDisplayName()); 
     byLocale.add(new MyLocale(locale)); 
     } 
    } 
    // Roll them out of the set. 
    ArrayList<String> list = new ArrayList<>(); 
    for (MyLocale l : byLocale) { 
     list.add(l.getCountry()); 
    } 
    return list; 
    } 

    public static void main(String[] args) throws InterruptedException { 
    // Some demo usages. 
    List<String> locales = listAll(); 
    System.out.println(locales); 
    } 
} 
8

어쨌든 내가 필요로하는 것은 미국과 영국을 상관없이 목록 상단에 배치하는 것입니다. 내가 가진 문제는 로케일에만 한정되어 있기 때문에 미국이나 영국에서 반환 할 색인이나 문자열을 분리 할 수 ​​없다는 것입니다. 다음 단계로이 로케일을 비교하기 위해 자신의 Comparator<Locale>를 구현해야처럼

그것은 소리 : 로케일이 같은 경우 하나의 로케일이 미국 0

  • 경우

    • , 반환 할 "승리"라는 하나의 로케일이 영국입니다
    • 경우 (기존의 행동, 즉 위임) o1.getDisplayCountry().compareTo(o2.getDisplayCountry())를 사용, 그렇지 않으면
    • 을 "승리"는
    • ,691을

    (이것은 영국 전에 미국을 넣어 것입니다.)

    그런 다음 사용자 정의 비교기의 인스턴스와 Collections.sort를 호출합니다.

    전에을 추출하기 전에 - 그런 다음 정렬 된 목록에서 추출하십시오.

  • 1

    당신이 일종의 수행 할 때 최고 값은 당신이 항상을에 원하는 값을 할 위치 네, 바로

    @Override 
        public int compare(String o1, String o2) { 
         if (o1.equals(TOP_VALUE)) 
          return -1; 
         if (o2.equals(TOP_VALUE)) 
          return 1; 
         return o1.compareTo(o2); 
        } 
    }) 
    

    자신의 비교기

    은, Collections.sort (worldCountriesByLocal, 새로운 비교기() {제공 위로

    1

    우선 순위를 지정하는 정수 (예 : 미국의 경우 0, 영국의 경우 1, 다른 사람의 경우 2), 일부 구분 기호 및 국가 이름으로 구성된 정렬 토큰을 사용하여 POJO를 작성합니다. 그 정렬 ID 및 t에 의해 키가되는 HashMap의 배열 그는 발로 POJO. 그런 다음 맵에서 키를 정렬하고 정렬을 반복하고 각 정렬 된 키의 일반 국가 이름을 검색합니다.

    예.

    2.Sweden 
    2.France 
    2.Tanzania 
    0.US 
    1.UK 
    

    종류의

    0.US 
    1.UK 
    2.France 
    2.Sweden 
    2.Tanzania 
    

    편집합니다 POJO는 당신이 국가 이름이 아닌 더 많은 필드가있는 경우에만 필요합니다.그것은 단지 국가 이름 일 경우 해시 키로 정렬 ID를 설정하고 val로 국가 이름을 설정하고 POJO 부분을 건너 뜁니다.