2015-09-05 87 views
-1

我需要在文本文件中对我的字符串进行排序。但每次我编译程序,文本文件看起来是这样的:如何使用java在文本文件中以数字方式对字符串进行排序?

10::name::birthday::address::email::fax::mobilenum::homeNum:: 
11::name::birthday::address::email::fax::mobilenum::homeNum:: 
1::name::birthday::address::email::fax::mobilenum::homeNum:: 
2::name::birthday::address::email::fax::mobilenum::homeNum:: 

这里是我的代码:

public static void main(String[] args) throws Exception { 

    BufferedReader reader = new BufferedReader(new FileReader("Phonebook.txt")); 
    LinkedList<String> contacts = new LinkedList<String>(); 
    String line; 
    while((line = reader.readLine()) != null) { 
     contacts.add(line); 
    } 

    Collections.sort(contacts); 

    FileWriter fileOut = new FileWriter("Phonebook.txt"); 

    for(String sorted:contacts) { 
     fileOut.write(sorted+"\n"); 
    } 

    fileOut.close(); 
} 
+1

看起来像什么? – Dici

+0

当你执行代码时会发生什么?你得到错误的结果/例外吗? – Pshemo

+0

我刚刚编辑了这个问题,对不起。 – nichkhun1

回答

1

你可以做这样的事情:

Collections.sort(contacts,new Comparator<String>() { 
     @Override 
     public int compare(String o1, String o2) { 
      if (o1.matches("^\\d+\\:\\:.+") && o2.matches("^\\d+\\:\\:.+")) { 
       return Integer.parseInt(o1.split("::")[0]) - Integer.parseInt(o2.split("::")[0]); 
      } 
      return 0; 
     } 
}); 

这将排序contacts按数字列出而不是按字母顺序排列。

+0

为什么试图抓住?听起来不好 – Dici

+0

非常感谢你! – nichkhun1

+0

@Dici我已经添加了它,以防''字符串没有预期的格式,它可以替换为几个检查。 – Titus

1

你可以得到你的线的整数部分,在TreeMap中你可以用它作为关键字,整行作为值。 TreeMap中让我们基于键我们的价值观排序,因为我们将使用Integer我们将在字符串的情况下得到的数字顺序,而不是按字母顺序排列像

您的代码可以是这样的:

Map<Integer, String> map = new TreeMap<>(); 

while((line = reader.readLine()) != null) { 


    map.put(Integer.valueOf(line.substring(0, line.indexOf("::"))), line); 
    //    |   |     | 
    //    |   |   find index of first :: 
    //    |  take part of string from start till first :: 
    //  convert String to Integer 
}  

for (String line : map.values()){ 
    System.out.println(line);//or write to file 
} 
+0

像这样,轻量级(没有新课堂)和高效 – Dici

2

10::name::birthday::address::email::fax::mobilenum::homeNum::

我可以在这里看到一个ClassContact。你应该更好地创建一个Contact类。

现在,对于每一行你有单独的Contact,假设第一个数字, 10对每个联系人都是唯一的。

创建,可以简单地转换你的StringContactObject,并通过调用方法为每一行,你将有Contact上榜的方法。

为了让Collection.sort(contactList)工作,你Contact类必须实现Comparable

例如:

public class Contact implements Comparable<Contact> { 

    @Override 
    public int compareTo(Contact contact) { 
     //add null check 
     return this.id.compareTo(contact.getId());//Considering Integer type for Id 
    } 
} 
相关问题