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

Community
  • 1
  • 1
user1203861
  • 1,177
  • 3
  • 15
  • 19

3 Answers3

0

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

double-beep
  • 5,031
  • 17
  • 33
  • 41
Noel M
  • 15,812
  • 8
  • 39
  • 47
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.

Jörg Beyer
  • 3,631
  • 21
  • 35
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
Mike Moe
  • 226
  • 2
  • 5