0

Possible Duplicate:
Java - Distinct List of Objects

i have a sorted array of huge size (around 3000 strings) , i need to create an object for each distinct string , therefore i need create an array of objects with the size equal to distinct strings in the original array.

any suggestions?

Thanks

3
  • 2
    Does : stackoverflow.com/questions/1019854/… do what you need ? Commented Feb 11, 2012 at 14:46
  • I seriously doubt 3000 can be considered a huge size. Maybe if it was 1 million ... Commented Feb 11, 2012 at 14:58
  • i know 3000 is not huge , but i meant processing time wise . Commented Feb 11, 2012 at 15:00

3 Answers 3

0

Well, if you need the distinct elements and not just the number, you may use a Set.

A Set is:

A collection that contains no duplicate elements.

You keep adding your elements to the set, and then just look at what the set contains.

Something similar to this:

public static String[] getDistinct(String[] input) {

    Set<String> distinct = new HashSet<String>();
    for(String element : input) {
        distinct.add(element);
    }

    return distinct.toArray(new String[0]);
}

Usage:

String[] input = new String[] {"a", "b", "a", "c", "a", "b", "d"};
String[] distinct = getDistinct(input);

for(String element : distinct) {
    System.out.println(element);
}

Result:

d b c a

Note that the order of the elements may not be preserved.

To find the number of the distinct elements, use:

getDistinct(input).length
Sign up to request clarification or add additional context in comments.

Comments

0

pseudo code:

previous = Null
sum_size = 0

for (String current: yourarray) {

    if (!current.equals(previous)) {
        sum_size += current.size()
    }
    previous = current
}

sum_size is the added size of distinct elements in your array.

2 Comments

He's not looking to count how many distinct objects there are
ok, I misunderstood that. I adjusted the answer to sum up the distinct strings
0

I think a Set is what you're looking for.

1 Comment

ok, I misunderstood that. I adjusted the answer to sum up the distinct strings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.