0
\$\begingroup\$

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); } } 
\$\endgroup\$
4
  • 3
    \$\begingroup\$Your code is either hypothetical (off-topic) or broken (also off-topic). What are you planning to do with the output? What's your usecase? Do you really need the speed?\$\endgroup\$
    – Pimgd
    CommentedApr 28, 2017 at 16:27
  • \$\begingroup\$Thanks Pimgd for replying. Yes, I really need the speed\$\endgroup\$
    – N. Leroy
    CommentedApr 28, 2017 at 16:46
  • 1
    \$\begingroup\$"Yes, I really need the speed" how do you know? Do you have a prove that your code it too slow?\$\endgroup\$CommentedApr 28, 2017 at 18:34
  • \$\begingroup\$@N.Leroy, there is a bug in the second (Java 8) approach. The call will not have any effect on the passed stringList contents, because you assign the resulting ArrayList to the reference that exists within the method scope only.\$\endgroup\$
    – Antot
    CommentedApr 29, 2017 at 11:23

1 Answer 1

2
\$\begingroup\$

Do you need them in a List in the first place?

Wouldn't it be easier to create it as a Set from the start, and only add elements if they're not null or empty.

That way all your conditions are checked: no null, empty or duplicates (implicit thanks to Set).

\$\endgroup\$

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.