Reputation: 25
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
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
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