简体   繁体   中英

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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