简体   繁体   English

在Java中按不同值对BufferedWriter字符串输出进行排序

[英]Sorting BufferedWriter string output by distinct value in java

I have this function: 我有这个功能:

It gets me all the data that I want but I need to sort the output by the work time. 它获取了我想要的所有数据,但我需要按工作时间对输出进行排序。 I can't figure out how to sort the data I'm getting. 我不知道如何对我得到的数据进行排序。

Any tips are appreciated. 任何提示表示赞赏。

raportBtn.setOnAction(event -> {

      Writer writer=null;
      try {
          File file = new File("C:/user/raport.txt");
          writer = new BufferedWriter(new FileWriter(file));
          for(Employee emp:listOfEmployees){
              String text = emp.getName() + " " + emp.getSurname()+ " " + emp.getRoom() + " " + emp.getWorkStart() + " " + emp.getWorkEnd() + " " + emp.getWorkTime() + "\n";
              writer.write(text);
          }
      } catch (IOException e) {
          e.printStackTrace();
      } finally{
          {
              try{
                  writer.flush();
              }catch(IOException e){
                  e.printStackTrace();
              }
              try{
                  writer.close();
              }catch(IOException e){
                  e.printStackTrace();
              }
          }
      }
  });

Everything you need is to implement a Comparator. 您所需要做的只是实现一个比较器。 Let's say that you want to sort the list by age(ascending). 假设您要按年龄(升序)对列表进行排序。 Then: 然后:

import java.util.Comparator;
public class EmployeesComparator implements Comparator<Employee> {

  @Override
  public int compare(Employee o1, Employee o2) {
    return o1.age - o2.age;
  }
}

Then, you can use it like this: 然后,您可以像这样使用它:

Collections.sort(listOfEmployees, new EmployeesComparator());

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM