0

I wrote a code like this which creates 150 employee objects from text files(150 text files) in a folder and stores it in a collection.

Those text files contains id,name and age of employess.

My problem is i want to sort id,name and age of those 150 employees..how should i write it..should i implement comparator or comparable interface? and to implement it. Please guide me

The code is below:

package com.fulcrum.emp;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class TestingColections {

    public static void main(String[] args) {

        File folder = new File("D:\\employee files");
        File[] listOfFiles = folder.listFiles();
        ArrayList<Employee> emp= new ArrayList<Employee>();;
        int id = 0;
        String name = null;
        int age = 0;
        for (File file : listOfFiles) {

            try {
                Scanner scanner = new Scanner(file);

                String tokens = "";
                String[] newtokens = null;

                while (scanner.hasNext()) {

                    tokens = tokens.concat(scanner.nextLine()).concat(" ");

                    tokens = tokens.replace("=", "|");
                    newtokens = tokens.split("[|\\s]");

                }

                id = Integer.parseInt(newtokens[1]);
                name = (newtokens[3] + " " + newtokens[4]);
                age = Integer.parseInt(newtokens[6]);



                emp.add(new Employee(id, name, age));




            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }


        }

        for(int i=0;i<emp.size();i++)
        {
            System.out.println(emp.get(i));
        }

    }

}
user2412380
  • 21
  • 3
  • 10

1 Answers1

0

One way to do this is use the Collections.sort() method which...

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface.

The Comparable interface defines only one method which...

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

So, if your Employee objects were to be sorted by ID, then the following would see you through:

public class Employee implements Comparable<Employee> {

    // Existing code


    public int compareTo( Employee e ) {
        return this.id - e.getId();
    }
} 

If you wanted to order by the employee's name, then the method could be this:

@Override
public int compareTo( Employee arg0 ) {
    return this.name.compareTo( arg0.getName() );
}

To sort the collection, use Collections.sort( emp ); before looping through and printing the values.

chooban
  • 9,018
  • 2
  • 20
  • 36