2011-12-15 2 views
3

콜렉션을 사용하여 정렬은 멋지다. Comparator를 사용하는 것보다 나에게 훨씬 낫다. 왜냐하면 같은 값을 여러 개 갖고 있기 때문에 쓰레기통에 버려지지는 않을 것이다. 하지만 컬렉션 자체 문제가있어, 2 + 그룹의 반복 숫자가 실제 작은 카운터 부분보다 작다고 생각하는 것 같습니다.컬렉션을 사용하여 값 정렬

예제에는 이러한 키와 값 ("katy 1", "mark 9", "john

앨리스 11 케이티 1 존 2 시아 22 크리스 44 마크 9

대신에 다음과 같은 2 ","앨리스 11 ","시아 22 ","크리스 44 ')과 그들을 정렬 올바른 순서로 katy 1 john 2 표시 9 alice 11 josiah 22 표시 44

어떻게 해결할 수 있습니까?

답변

4

당신이 문자열을 통과하고 있기 때문에, 컬렉션 더있다 이 문자열을 어떻게 해석 할 것인지를 알려주는 방법 (즉, 문자열 안에있는 숫자로 정렬). 당신은 더 명백해야합니다.

당신은 기본적으로 두 가지 옵션이 있습니다

옵션 1 :

public class Person implements Comparable<Person> { 

    private String name; 
    private int number; 

    public Person(String name, int number) { 
     this.name = name; 
     this.number = number; 
    } 

    public int compareTo(Person p) { 
     if(this.number > p.number) return 1; 
     if(this.number < p.number) return -1; 
     return 0; 
    } 
} 

다음 :

List<Person> persons = new ArrayList<Person>(); 
persons.add(new Person("alice", 11)); 
persons.add(new Person("katy", 1)); 
// etc. 
Collections.sort(persons); 
이름과 번호를 캡슐화 번호로 비교를 구현하는 새로운 데이터 유형을 만들기를

옵션 2 : 문자열을 키 - 값 쌍으로 바꾸고 키 - 값 쌍으로 자동으로 키에 의해 정렬 된 값을 유지 TreeMap :

TreeMap<Integer, String> map = new TreeMap<Integer, String>(); 
map.put(11, "alice"); 
map.put(1, "katy"); 
// etc. 
+0

완벽하게 일했습니다. 감사합니다. – ChrisD3

0

문자열과 정수를 구분하는 코드를 리팩터링하는 것이 가장 좋습니다.

당신이 그것을 할 수 없거나 원하지 않는다면, 당신은 자신의 비교자를 제공해야합니다.

@Override 
public int compare(String o1, String o2) { 
    Integer i1 = Integer.parseInt(o1.replaceAll("[^0-9]", "")); 
    Integer i2 = Integer.parseInt(o2.replaceAll("[^0-9]", "")); 
    return i1.compareTo(i2); 
} 

같은 뭔가 그럼 당신은 당신이 당신의 자신의 비교기를 작성해야 Collections.sort(List, Comparator)

List<String> list; // ... 
Collections.sort(list, new YourComparator()); 
0

사용할 수 있습니다. 문자열을 숫자로 비교하려면 숫자로 변환해야합니다. 그렇지 않으면 "22"< "4"에도 불구하고 22> 4

그러나 기본 비교기로 첫 번째 주문을받는 방법을 알 수 없습니다.

1

난 당신이 Comparable 인터페이스를

class Person implements Comparable<Person >{ 

     String name; 
     Integer number; 
     public int compareTo(Person o) { 

     return number.compareTo(o.number); 
    } 

} 
0

확인이 예

편집을 구현 Person 클래스를 만들 수 있다고 생각

public static void main(String arg[]){ 

    List<String> l = Arrays.asList(new String[]{"katy 1","mark 9","john 2","alice 11","josiah 22","chris 44"}); 

    Collections.sort(l, new Comparator<String>() { 
     public int compare(String x, String y) { 
      Integer a = Integer.parseInt(x.substring(x.indexOf(" ")).trim()); 
      Integer b = Integer.parseInt(y.substring(y.indexOf(" ")).trim()); 
      return a.compareTo(b); 
     } 
    }); 
    System.out.println(l.toString()); 
} 
+1

왜 그렇게 복잡합니까? 'Integer' 클래스는 완벽하게 자체 비교를 수행 할 수 있습니다. –

+0

@ JohanSjöberg 맞습니다. 사실 나는이 개념을 정리해 주셔서 감사합니다. – Pratik

2
  1. 저장하시오 Map<String, Integer>로 데이터 - 단일 문자열로 두 가지 데이터 유형을 벼락 공부를하지 않습니다.
  2. 는 항목은 목록으로 설정하고 주문지도 여기

로 설정 한 분류 항목을 넣어

  • 그것을 분류를 할 것 몇 가지 코드입니다하기 :

    public static void main(String[] args) { 
        // Set up and load the map 
        Map<String, Integer> nameAgeMap = new HashMap<String, Integer>(); 
        nameAgeMap.put("katy", 1); 
        nameAgeMap.put("chris", 44); 
        nameAgeMap.put("alice", 11); 
        nameAgeMap.put("josiah", 22); 
        nameAgeMap.put("john", 2); 
    
        // Create-and-load a List of entries 
        List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(nameAgeMap.entrySet()); 
        // Sort the list using a custom Comparator that compares the ages 
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { 
         public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { 
          return o1.getValue().compareTo(o2.getValue()); 
         }}); 
    
        // Load the entries into a Map that preserves insert order 
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); 
        for (Map.Entry<String, Integer> entry : entries) 
         sortedMap.put(entry.getKey(), entry.getValue()); 
    
        // All done - let's see what we got 
        System.out.println(sortedMap); 
    } 
    

    출력 :

    {katy=1, john=2, alice=11, josiah=22, chris=44} 
    
  • 1

    오름차순으로 $ 값에 대한 논리를 정렬하십시오. 내림차순으로 필요한 경우 변수 i1과 i2를 교환하십시오.

    public static void main(String[] args) { 
    
    
    
        List<String> l_oTestList = new ArrayList<String>(); 
        l_oTestList.add("$10000 - $12000"); 
        l_oTestList.add("$50 - $100"); 
        l_oTestList.add("$10000 - $12000"); 
        l_oTestList.add("$100 - $150"); 
        l_oTestList.add("$150 - $200"); 
        l_oTestList.add("$200 - $250"); 
        l_oTestList.add("$0 - $10"); 
        l_oTestList.add("$10 - $20"); 
        l_oTestList.add("$20 - $50"); 
        l_oTestList.add("$250 - $500"); 
        l_oTestList.add("$500 - $750"); 
        l_oTestList.add("$750 - $1000"); 
        l_oTestList.add("$1000 - $1250"); 
        l_oTestList.add("$1250 - $10000"); 
        List<String> l_oTestList1 = sort(l_oTestList); 
        System.out.println(l_oTestList1.toString()); 
    } 
    
    private static List<String> sort(List<String> pTestList) { 
        Collections.sort(pTestList, new Comparator<String>() { 
         public int compare(String o1, String o2) { 
          Integer i1 = Integer.parseInt(o1.replace("$", "").substring(0,o1.indexOf("-")-2).trim()); 
          Integer i2 = Integer.parseInt(o2.replace("$", "").substring(0,o2.indexOf("-")-2).trim()); 
          return (i2 > i1 ? -1 : (i2 == i1 ? 0 : 1)); 
         } 
        }); 
        return pTestList; 
    } 
    
    관련 문제