I am looking for the best and fast way(performance wise) to remove null, empty and duplicate elements in arraylist of string. This method can be called maximum 700 times and the list can contains around 13 strings maximum. I have created a test case and I can not get an exact value of the execution time to make the difference between both codes below If someone has an idea, thanks.
//Delete null, empty and duplicate element in sting arrayList public static void removeNullAndEmptyAndDuplicateElementsInList(List<String> stringList) { if (stringList != null && !variablesList.isEmpty() && variablesList.size()>1) { for (int x = stringList.size() - 1; x >= 0; x--) { if (stringList.get(x) == null || stringList.get(x).isEmpty()) { stringList.remove(x); } else { for (int y = 0; y < x; y++) { if (stringList.get(x).equals(stringList.get(y))) { stringList.remove(x); break; } } } } } }
or Java 8
public static void removeNullAndEmptyAndDuplicateElementsInList(List<String> stringList) { if (stringList != null && !variablesList.isEmpty() && variablesList.size()>1) { Set<String> stringListSet = stringList.stream() .filter(var -> (var != null && !var.isEmpty())) .distinct() .collect(Collectors.toCollection(HashSet::new)); stringList = new ArrayList<String>(stringListSet); } }
stringList
contents, because you assign the resultingArrayList
to the reference that exists within the method scope only.\$\endgroup\$