-2

I want to get a new array of strings without duplicate values from the original array of strings. For example if the original array is {a b b b c d, a a b b c, a b c c }, my new string should not contain duplicates. I have not been able to figure it out at all as all the solutions in different threads talk about single string arrays and not multiple ones like this. I don't know if I have to use the .split function and add to a hashset and then add it back to a new list that I created.

Any help would be appreciated.

  • What is the expected result? An array ["abcd", "abc", "abc"]? Something else? – TheJavaGuy-Ivan Milosavljević Feb 14 '22 at 10:53
  • 1
    does this answer your question? https://stackoverflow.com/q/10366856/8283737 – Arun Gowda Feb 14 '22 at 10:57
  • Do you have an array of arrays of strings where the strings are a, b or c, like [["a", "b", "b"], ["a", "a", "b", "b"]]? You say "my new string should not contain duplicates", do you mean array? Would your example of {a b b b c d, a a b b c, a b c c } leave an array of three arrays, ["a","b","c","d"], ["a","b","c"] and ["a","b","c"]? – JollyJoker Feb 14 '22 at 10:57
  • Does this answer your question? [Delete duplicate strings in string array](https://stackoverflow.com/questions/10366856/delete-duplicate-strings-in-string-array) – Arun Gowda Feb 14 '22 at 10:59
  • You are mixing a lot of terminology so it is not clear what you are asking. Do you have a List or a array? Are you trying to create a new collection or affect the existing collection? Are you removing duplicate letters from each String or are you removing duplicate Strings from the collection? Your example adds nothing because it does not include the expected result of that data set. – vsfDawg Feb 14 '22 at 11:47
  • @JollyJoker yes that is the expected output i want. – Affan Naushahi Feb 21 '22 at 10:34

1 Answers1

1

Simply use a Set:

As explained in the first line in the docs:

A collection that contains no duplicate elements.

String[] array = { "a", "b", "b", "b", "c", "d", "a", "a", "b", "b", "c", "a" ,"b", "c", "c" };
Set<String> set = new HashSet<String>(Arrays.asList(array));

The result is [a, b, c, d].

Or in one line using Java8:

array = Arrays.stream(array).distinct().toArray(String[]::new);

You can check this article as a reference.

J.F.
  • 13,927
  • 9
  • 27
  • 65