Currently I am attempting to remove ALL duplicates from a list. However, from what I gather, this will only remove them if the total amount is divisible by 2. How can I edit it so it will get all copies, if it were 3 or 5, or more?
if(check.size() < recipes.size()) { //check is a set, checking for copies.
logger.warning("We found a copy of names, please change them! We will be disabling those recipes to disable errors.");
for(int i = 0; i < recipes.size(); i++) {
for(int j = 0; j < recipes.size(); j++) {
if(recipes.get(i) == recipes.get(j) && i != j) {
logger.warning("We found copies of " + recipes.get(i));
recipes.remove(i);
recipes.remove(j);
}
}
}
}
Currently it will only remove 2 values from the list.
Also, if there are copies, I don't want 1 copy remaining, I wish to remove them all as to avoid errors later on.
You have multiple options, one of which would be to use an implementation of Set
as it is inherently collection that compels to uniqueness. Another one of the options would be to create a new list and use lambdas to get distinct elements, for example let's say you want to copy only unique/distinct elements from "recipes" list to new list "recipesUnique", you could do this:
ArrayList<T> recipesUnique = new ArrayList<>();
recipes.stream().distinct().forEach(recipesUnique::add);
There are many more possible solutions, if you ask me, lambdas are the simplest one if you are obliged to use List, otherwise just use Set
.