2015-04-01 114 views
0

我讀了文件,其中每一行看起來是這樣的: userNameageaward排序按索引的Java

我需要編程使兩個排序類型:by userNameby age。我對第一個沒有任何問題,但我不知道如何在這樣的例子中按年齡排序.. 我試着在每一行中用年齡切換名稱,但它不起作用。 這就是我所(它基本上只是從文件中讀取並顯示它):

try{ 
      File file=new File(path); 
      BufferedReader read=new BufferedReader(new FileReader(file)); 
      String line=read.readLine(); 
      all+=line+"\n"; 
      while(line!=null){ 
       line=save.readLine(); 
       all+=line+"\n"; 
      } 

      String [] tabUsers=all.split("\n");  




      String display="";    
      for(int a=0;a<tabUsers.length-1;a++){   
       display+=tabUsers[a]+"\n"; 
      } 

      for(int c=0;c<tabUsers.length-1;c++){ 
        System.out.println(tabUsers[c]); 

     } 


     } 
     catch(Exception ex){ 

     } 

任何想法?

我已經試過這一點,但沒有奏效:

for(int b=0;b<tabUsers.length-1;b++){ 
       String eachLine =tabUsers[b]; 
       String [] splitLine=eachLine.split(","); 
       splitLine[0]=splitLine[1]; 
      } 
+1

你是什麼意思「我知道按姓名排序......但我不按年齡排序」。我只是沒有看到它在'String'上對_alphabetically_進行排序所產生的差異,或者只是通過'int'上的自然順序關係來進行排序......?你能說出你在做什麼嗎? – 2015-04-01 11:38:30

+0

至於名字我簡單地使用這行:Arrays.sort(tabUsers,0,tabUsers.length-1); – chatteVerte 2015-04-01 11:43:28

+0

您是否嘗試過分割每一行並獲取它們的年齡?如果你有它,你可以用它來排序,對吧? – 2015-04-01 11:48:47

回答

0

首先從每一行獲取姓名和年齡。然後你可以把東西放在兩個treeMaps,一個名字鍵和其他Age鍵上。例如:

String[] lines = new String[3]; 
    lines[0] = "Michael 25 Award_1"; 
    lines[1] = "Ana 15 Award_2"; 
    lines[2] = "Bruno 50 Award_3"; 

    String[] parts; 
    Map<String, String> linesByName = new TreeMap<String, String>();   
    Map<Integer, String> linesByAge = new TreeMap<Integer, String>(); 

    for (String line : lines) { 
     parts = line.split(" "); 
     linesByName.put(parts[0], line); 
     linesByAge.put(Integer.parseInt(parts[1]), line); 
    } 

    System.out.println("Sorted by Name:"); 

    for (Map.Entry<String, String> entry : linesByName.entrySet()) { 
     System.out.println(entry.getValue()); 
    } 

    System.out.println("\nSorted by Age:"); 

    for (Map.Entry<Integer, String> entry : linesByAge.entrySet()) { 
     System.out.println(entry.getValue()); 
    } 
1

讀取數據到對象的集合是這樣的:

public class User { 
    final String name; 
    final int age; 
    final String award; 

    public User(String name, int age, String award) { 
     this.name = name; 
     this.age = age; 
     this.award = award; 
    } 
} 

然後使用Collections.sortComparator<User>排序:

User bob = new User("Bob", 44, null); 
User zack = new User("Zack", 13, null); 
List<User> users = Arrays.asList(bob, zack); 

//sort by age 
Collections.sort(users, new Comparator<User>() { 
    @Override 
    public int compare(User user1, User user2) { 
     return Integer.compare(user1.age, user2.age); 
    } 
}); 

//sort by name 
Collections.sort(users, new Comparator<User>() { 
    @Override 
    public int compare(User user1, User user2) { 
     return user1.name.compareTo(user2.name); 
    } 
});