Evan
Evan

Reputation: 374

Deleting Duplicates in a List

I am managing an email listserv for my club. I need to sort the email addresses from a txt file, delete the duplicates, and then ouput them so that I may easily organize them. Most of my code is spliced together from various sources online since I have very minimal programming skills right now. This is what I have so far:

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class ReadAllLines {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Path textFile_path = Paths.get("V:/", "Entrepreneurship Club Email List.txt");

        Charset charset = Charset.forName("ISO-8859-1");
        try {
            //Reads txt file
            List<String> lines = Files.readAllLines(textFile_path, charset);

            //Sorts txt file alphabetically
            Collections.sort(lines);

            //prints txt file
            for (String line : lines) {
                System.out.println(line);
            }
        //File Not Found Error
        } catch (IOException e) {
            System.out.println(e);
        }
    } 
}

Upvotes: 1

Views: 68

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

I need to sort the email addresses from a txt file, delete the duplicates, and then ouput them so that I may easily organize them.

In that case, use a SortedSet

Set<String> set = new TreeSet<>(Files.readAllLines(textFile_path, charset));

set will be sorted with duplicates ignored.

In Java 8, you can do

Set<String> set = Files.lines(textFile_path, charset)
                       .sorted()
                       .collect(toSet());

Upvotes: 5

Related Questions