2016-11-08 1 views
0

현재 파일 내의 이름 만 정렬 한 시점이지만 나이를 정렬 할 수 있도록 만들고 싶습니다. 또 다른 문제는 동일한 이름을 가지려고하지만 여러 연령대로 분류하려고하는 것입니다.동시에 숫자와 이름을 모두 정렬하는 방법

import java.io.BufferedReader; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.lang.reflect.Array; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.List; 


public class MultiKey { 

    public static void main(String[] args) { 
     File textFile = new File("H:\\Names_ages.txt"); 
     FileReader in; 
     BufferedReader readFile; 
     String lineOfText; 

     try { 
      in = new FileReader(textFile); 
      readFile = new BufferedReader(in); 
      BufferedReader reader = new BufferedReader(new FileReader(textFile)); 
      List<String> results = new ArrayList<String>(); 
      while ((lineOfText = readFile.readLine()) != null) { 
       results.add(lineOfText); 

      } 
      Collections.sort(results); 
      System.out.println(results); 


      readFile.close(); 
      in.close(); 
     } catch (FileNotFoundException e){ 
      System.out.println("File does not exist or could not be found"); 
      System.err.println("FileNotFoundException: "+ e.getMessage()); 
     } catch (IOException e){ 
      System.out.println("Problem reading file"); 
      System.err.println("IOException: " + e.getMessage()); 
     } 
    } 
} 
+1

여러 가지 방법으로 컬렉션을 정렬 할 경우, 당신이 작성 비교기하여이 작업을 수행 할 수 있습니다, http://stackoverflow.com/questions/5245093/using-comparator-to- 두를 만드는 elow make-custom-sort 비교자를 사용하면 지정된 메소드를 기반으로 콜렉션을 정렬 할 수 있습니다. – chatton

+0

바로 지금 얻고있는 결과는 다음과 같습니다. [Abrams 15, Alexander 22, Herkman 12, Jones 11, Jones 14, Jones 2, Jones 9, Smith 17, Smith 19, Smith 20, Tippurt 42] –

+0

You 또한 [자원을 사용해보십시오 (try-with-resources)] (https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)를 조사해야합니다. – bradimus

답변

0

일반적인 접근 방식은 다음과 같습니다 : 지금 내 코드는 다음과 같이 보입니다

  • 구문 분석 각 라인을 두와 예에 (그것을 에 대한 클래스 "사람"을 캡슐화 객체를 생성 "name"및 "age"필드) 이 구문 분석을 수행하는 방법은 파일 의 줄 형식에 따라 다릅니다. 줄 의 값이 쉼표로 구분되어 있으면 String.split (",")을 사용할 수 있습니다.

  • 캡슐화 객체를 목록에 추가 한 다음 비교자를 사용하여 정렬하십시오. java.util.Collections.sort (Comparator)를 사용합니다.

물론 캡슐화 객체 목록을 사용하면 훨씬 쉽게 할 수 있습니다. 같은 이름이지만 나이가 다른 인물을 찾습니다.

1

논리 :

  • 당신이에 정렬해야 할 속성에 대한 별도의 홀더를 만듭니다.
  • 해당 Person 개체에 Comparator를 적용하십시오.

    import java.io.BufferedReader; 
    import java.io.File; 
    import java.io.FileNotFoundException; 
    import java.io.FileReader; 
    import java.io.IOException; 
    import java.lang.reflect.Array; 
    import java.util.ArrayList; 
    import java.util.Arrays; 
    import java.util.Collections; 
    import java.util.List; 
    
    
    public class MultiKey { 
    
        public static void main(String[] args) { 
         File textFile = new File("H:\\Names_ages.txt"); 
         FileReader in; 
         BufferedReader readFile; 
         String lineOfText; 
    
         try { 
          in = new FileReader(textFile); 
          readFile = new BufferedReader(in); 
          BufferedReader reader = new BufferedReader(new FileReader(textFile)); 
          List<Person> results = new ArrayList<Person>(); 
          while ((lineOfText = readFile.readLine()) != null) { 
           //split here the line into name and age separate variables basedon delimiter available between them. 
           Person p = new Person(name,age); 
           results.add(p); 
    
          } 
          order(results); 
          System.out.println(results); 
    
    
          readFile.close(); 
          in.close(); 
         } catch (FileNotFoundException e){ 
          System.out.println("File does not exist or could not be found"); 
          System.err.println("FileNotFoundException: "+ e.getMessage()); 
         } catch (IOException e){ 
          System.out.println("Problem reading file"); 
          System.err.println("IOException: " + e.getMessage()); 
         } 
        } 
    } 
    
    private static void order(List<Person> persons) { 
    
        Collections.sort(persons, new Comparator<Person>() { 
    
         public int compare(Object o1, Object o2) { 
    
          String x1 = ((Person) o1).getName(); 
          String x2 = ((Person) o2).getName(); 
          int sComp = x1.compareTo(x2); 
    
          if (sComp != 0) { 
           return sComp; 
          } else { 
           Integer x1 = ((Person) o1).getAge(); 
           Integer x2 = ((Person) o2).getAge(); 
           return x1.compareTo(x2); 
          } 
        }}); 
    } 
    
    public class Person{ 
    private String name; 
    private int age; 
    
    public String getName(){ 
    return this.name; 
    } 
    
    public void setName(String name){ 
    this.name = name; 
    } 
    
    public int getAge(){ 
    return this.age; 
    } 
    
    public vois setAge(int age){ 
    this.age = age; 
    } 
    

    } 하나 개 이상의 공간도 시도 패턴 \\s+ 대신 공백

    또는 예상되는 경우

0

당신은 체인 Comparator

Comparator<String> byName = Comparator.comparing(s -> s.split(" ")[0]); 
    Comparator<String> byAge = Comparator.comparingInt(s -> Integer.parseInt(s.split(" ")[1])); 

    try (BufferedReader br = new BufferedReader(new FileReader("filePath"))) { 
     List<String> sorted = br.lines().sorted(byName.thenComparing(byAge)).collect(Collectors.toList()); 
     return sorted; 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

thenComparing을 사용할 수 있습니다 우리는 b처럼 Comparator을 만들 수 있습니다. 대신 Comparator

Comparator<String> c = Comparator.<String, String> comparing(s -> s.split("\\s+")[0]) 
      .thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1])); 
관련 문제