-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.

6
  • What is the expected result? An array ["abcd", "abc", "abc"]? Something else? Commented Feb 14, 2022 at 10:53
  • 1
    does this answer your question? stackoverflow.com/q/10366856/8283737 Commented Feb 14, 2022 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"]? Commented Feb 14, 2022 at 10:57
  • Does this answer your question? Delete duplicate strings in string array Commented Feb 14, 2022 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. Commented Feb 14, 2022 at 11:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.