Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Given an array like the one below, I was wondering if there is an easy way to turn this array into an array with unique values only?

This is given:

   numbers={5,5,4,3,1,4,5,4,5} 

Turn it into a result array like this, preserving the original order:

   {5,1,2,3,4} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
146 views
Welcome To Ask or Share your Answers For Others

1 Answer

In Java 8, use IntStream to get unique elements of an array

int[] noDuplicates = IntStream.of(array).distinct().toArray();

The simplest way would be to create set from the array.

Integer[] array = ...
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(array ));

and then you can retrieve the array using:

set.toArray()

use LinkedHashSet if you want to maintain the order or TreeSet if you want to have it sorted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...