Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help sorting arraylist alphabetically

I need help sorting an array list that contains all the names in the names.txt file. I tried Collections.sort() like suggested but the list is still unsorted. What am I doing wrong?

private static void Excerise04(String fname) throws FileNotFoundException {
    Scanner filescanner = new Scanner(new File(fname));
    while (filescanner.hasNext()) {
        String line = filescanner.next();
        ArrayList<String> set = new ArrayList<>();
        set.add(line);
        Collections.sort(set);
        System.out.println(set);
    }
}

Names.txt

Slater, Kendall
Lavery, Ryan
Chandler, Arabella "Babe"
Chandler, Stuart
Kane, Erica
Chandler, Adam Jr
Slater, Zach
Montgomery, Jackson
Chandler, Krystal
Martin, James
Montgomery, Bianca
Cortlandt,  Palmer
Devane, Aidan
Madden, Josh
Hayward, David
Lavery,k Jonathan
Smythe, Greenlee
Cortlandt, Opal
McDermott, Annie
Henry, Di
Grey, Maria
English, Brooke
Keefer, Julia
Martin, Joseph
Montgomery, Lily
Dillon,  Amanda
Colby, Liza
Stone, Mary Frances
Chandler, Colby
Frye, Derek
Montgomery, Reggie
Montgomery, Sean
Santos, Hayley
Santos, Mateo
Dillon, Janet
Jefferson, Kelsey
Chandler, Marian
Fargate, Myrtle
Henry, Del
Codahy, Livia
Warner, Anita
Lavery, Spike
Martin, Ruth
Montgomery, Barbara

I tried adding Collections.sort(set) to sort array list alphabetically but nothing happened, it didn’t sort, just printed out unsorted list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should declare the List of lines outside the loop in order to collect all the lines together.

List<String> set = new ArrayList<>();
// lines would probably be a better variable name

Use Scanner#nextLine instead of Scanner#next to read the entire line, including whitespace.

String line = filescanner.nextLine();

Finally, sort and display the List after the loop, after you’ve read everything.

while (filescanner.hasNext()) {
    // ...
}
Collections.sort(set);
System.out.println(set);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading