-6

Is it possible to make an array of an array? What I am trying to do is basically make a an array of another array without duplicates.

For example:

String[] colour ={"blue","blue","red","blue","red","red","orange","yellow","purple","green","blue"};

and then make a new array from String[] colour into:

String[] uniqueColour = {"blue","red","orange","yellow","purple","green"}

using a function and without just declaring it? Cause lets say I change all the values of String[] Colour and turn it into

String[] Fruits = {"Apple","Banana","Orange","Tomato","Apple","Banana"}

then without doing or changing anything else the function should create

String[] uniqueColour ={"Apple","Banana","Orange","Tomato"}

Does such a thing exist? Sorry for the trouble. And I'm new to java as well.

A thank you to anyone who can contribute or help me out.

EDIT: Okay so by using this: - Thanks to Doorknob's answer

Set<String> uniqueSet = new HashSet<String>(Arrays.asList(colour));
String[] uniqueColours = uniqueSet.toArray(new String[0]);

how would I then try to display it as:

Blue
Red
Yellow
Green
Purple
ect

instead of [Blue,Red,Yellow,Green,Purple,etc]

4
  • "then without doing or changing anything else the function should create" - Then how do you think things are changed? Commented Apr 18, 2013 at 12:13
  • Is it possible to make an array of an array? Yes , but what are you trying to achieve is very vague ! Commented Apr 18, 2013 at 12:13
  • 1
    When we say "array of arrays" we mean a two-dimensional array -- an array where each element is another array. You seem to be asking about removing duplicates, so your wording is quite confusing. Commented Apr 18, 2013 at 12:15
  • Oh I'm sorry guys I am terrible at explaining things I'll edit it. Commented Apr 18, 2013 at 12:18

1 Answer 1

1

Use a Set to remove duplicates:

Set<String> uniqueSet = new HashSet<String>(Arrays.asList(colour));
String[] uniqueColours = uniqueSet.toArray(new String[0]);

To display it in the way you wanted:

for (String s : uniqueColors) System.out.println(s);
Sign up to request clarification or add additional context in comments.

3 Comments

How would I display the String[] Unique Colours? By that I mean instead of it showing up as [blue,red,orange,yellow,purple,green] I want to display it as Blue\nRed\nOrange\nYellow\nPurple\nGreen
@Leo Why the unaccept? Did it not work?
@Leo Is there anything wrong with this solution?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.