Alistair Osborne
Alistair Osborne

Reputation: 25

Create a new list of strings using another but without duplicates

I've looked at multiple different answer and questions but none seem to be giving the result I would like. my issue is that I have a .txt file with 426458 states (disregarding the rules) of noughts and crosses with the format shown below.

[E][E][E]
[E][E][E]
[E][E][E]

[X][X][X]
[O][O][O]
[E][E][E]

I load the file using this:

Scanner sc = new Scanner(new File("src/AllPlayerOneStates.txt"));
    sc.useDelimiter("\r");
    List<String> lines = new ArrayList<String>();
    while (sc.hasNextLine()) {
      lines.add(sc.next());
    }

This creates a list with every element being a state then I would like to create a new list without duplicate states.

I've tried using StringBuilder to simply output all the unique states but it gives me a number much less than expected aswell as looping through each element and comparing it to all the rest but I may have done it wrong as it told me the amount of unique states was larger than 426458. I'm relatively new to programming.

Upvotes: 1

Views: 145

Answers (2)

VHS
VHS

Reputation: 10184

This creates an array with every element being a state then I would like to create a new array without duplicate states.

Try the following way:

Set<String> set = new HashSet<String>(lines);
List<String> newList = new ArrayList<String>(set);

Here newList is your new List of states that doesn't contain duplicates.

Upvotes: 3

Darshan Mehta
Darshan Mehta

Reputation: 30839

You can use Set instead of List and it will remove the duplicates itself, e.g.:

Set<String> lines = new HashSet<String>();
while (sc.hasNextLine()) {
  lines.add(sc.next());
}

Once this while loop finishes, lines.size() will give you number of unique rules.

If you want to preserve the order, you can use LinkedHashSet instead of HashSet.

Upvotes: 2

Related Questions