I
I
infoguides2019-01-21 18:42:28
Java
infoguides, 2019-01-21 18:42:28

How to count the number of unique elements in an array?

A seemingly simple question, how to count the number of unique elements in an array int[] N
for example
int[] N = {1,2,3,4,5,6,7,6,8,9,1,2,3}
First What comes to mind is to create a second array key=>value where key = is the value from the first array and value = is the number of elements in the input array.
Roughly speaking in PHP it would be like this

foreach($N as $k=> $v) {
  if (isset($newArray[$v])) {
    $newArray[$v] = $newArray[$v] + 1;
  } else {
    $newArray[$v] = 1;
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
al_gon, 2019-01-21
@infoguides

int[] N = {1, 2, 3, 4, 5, 6, 7, 6, 8, 9, 1, 2, 3};
  Integer[] wrappedN = Arrays.stream(N)
                .boxed()
                .toArray(Integer[]::new);
  Set<Integer> resultSet = new HashSet<Integer>(Arrays.asList(wrappedN));
  System.out.println(resultSet.size());

System.out.println(Arrays.stream(N).boxed().collect(Collectors.toSet()).size());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question