简体   繁体   中英

Having problems with the Stream API sorting and filtering

I have a Citizen class which contains the reference class that I am utilizing. What I want to do is to pass the data that I read from a file into the Citizen class, store these data into an array or list and sort it using the stream api

Here's what I am working on currently

The readCSV method which reads the data.csv file, passes it in the reference class and adds it onto the List:

public static ArrayList<Citizen> readCSV(String datafile) throws FileNotFoundException {
    ArrayList<Citizen> citizenList = new ArrayList<>();
    String contents;
    BufferedReader brd = new BufferedReader(new FileReader(datafile));
    try {
        while ((contents = brd.readLine()) != null) {
            String[] st = contents.split(",(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)");
            String firstName = st[1];
            String lastName = st[0];
            String email = st[2];
            String address = st[3];
            int age = Integer.parseInt(st[4]);
            boolean resident = false;
                if ((st[5].compareToIgnoreCase("Resident")  == 0)) {
                    resident = true;
                }
            int district = Integer.parseInt(st[6]);
            String gender = st[7];
                if (st[7].compareToIgnoreCase("Female") == 0) {
                    gender = "female";
                } else if (st[7].compareToIgnoreCase("Male") == 0) {
                    gender = "male";
                }

            citizenList.add(new Citizen(lastName, firstName, email, address, age, resident, district, gender));
        } // end of while loop
    } // end of try
    catch (Exception e) {
        System.out.println("File not found:" + e.getMessage());
    } // end of Catch
    return citizenList;
}// end of ReadFile method

And here's the method that is supposed to sort the data from the read file:

  public static List<Citizen> getName(List<Citizen> citizens, String path) throws FileNotFoundException {
    ArrayList<Citizen> list = readCSV(path);
    Citizen foundCitizen = new Citizen();

    list.stream().sorted(Comparator.comparing(Citizen::getLastName)).collect(Collectors.toList());

    return list;

Here's the print method that I call in the main method. This method will will inbvoke the getName method and print the sorted values:

public static void printName(List<Citizen> citizens, String path) throws FileNotFoundException {
    ArrayList<Citizen> shitizen = new ArrayList<>(getName(readCSV(path), path));
    for (Citizen e : shitizen) {
        System.out.println(e);
    }
}

The problem is when I try to run the program, it only prints out the values in the order that is same from the file read. It does not sort it. I am trying to find out what is the problem with the code and how to correct it so that the sorted method works. Your help will be hugely appreciated. Thank you!

A stream does not modify your existing list, it creates a new list when you call collect() . What you need to do is assign the result of this method to your list variable:

list = list.stream()
           .sorted(Comparator.comparing(Citizen::getLastName))
           .collect(Collectors.toList());

Or alternatively:

return list.stream()
           .sorted(Comparator.comparing(Citizen::getLastName))
           .collect(Collectors.toList());

You can also just sort your list in place, no need for streams:

list.sort(Comparator.comparing(Citizen::getLastName));

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