I am Java beginner, I found a few topics regarding this theme, but none of them worked for me.
I have an array like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
and I would need to get this output:
1, 2, 3, 4, 5
Every item from that array just once.
But how to get it?
b4hand
9,5054 gold badges44 silver badges50 bronze badges
asked Apr 1, 2013 at 21:26
user984621user984621
45.9k73 gold badges224 silver badges405 bronze badges
1
The simpliest solution without writing your own algorithm:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
answered Apr 1, 2013 at 21:29
Maxim KolesnikovMaxim Kolesnikov
5,0555 gold badges37 silver badges66 bronze badges
4
You can use a Set<Integer>
and save lot of time since it holds unique elements. If you aren’t allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort
.
I’ll post the Set<Integer>
code:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
System.out.println(x);
}
Note that I prefer to use LinkedHashSet
as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2}
then the output will be 2, 1
and not 1, 2
.
answered Apr 1, 2013 at 21:27
Luiggi MendozaLuiggi Mendoza
84.8k16 gold badges153 silver badges328 bronze badges
6
In Java 8:
final int[] expected = { 1, 2, 3, 4, 5 };
final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };
final int[] distinct = Arrays.stream(numbers)
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);
final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };
final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
.sorted()
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
answered Jul 17, 2014 at 13:32
2
//Running total of distinct integers found
int distinctIntegers = 0;
for (int j = 0; j < array.length; j++)
{
//Get the next integer to check
int thisInt = array[j];
//Check if we've seen it before (by checking all array indexes below j)
boolean seenThisIntBefore = false;
for (int i = 0; i < j; i++)
{
if (thisInt == array[i])
{
seenThisIntBefore = true;
}
}
//If we have not seen the integer before, increment the running total of distinct integers
if (!seenThisIntBefore)
{
distinctIntegers++;
}
}
answered Apr 4, 2013 at 21:13
IcemanindIcemanind
47.2k50 gold badges171 silver badges294 bronze badges
Below code will print unique integers have a look:
printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
static void printUniqueInteger(int array[]){
HashMap<Integer, String> map = new HashMap();
for(int i = 0; i < array.length; i++){
map.put(array[i], "test");
}
for(Integer key : map.keySet()){
System.out.println(key);
}
}
b4hand
9,5054 gold badges44 silver badges50 bronze badges
answered Apr 1, 2013 at 21:36
user_CCuser_CC
4,6763 gold badges19 silver badges15 bronze badges
Simple Hashing will be far efficient and faster than any Java inbuilt function:
public class Main
{
static int HASH[];
public static void main(String[] args)
{
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
HASH=new int[100000];
for(int i=0;i<numbers.length;i++)
{
if(HASH[numbers[i]]==0)
{
System.out.print(numbers[i]+",");
HASH[numbers[i]]=1;
}
}
}
}
Time Complexity: O(N), where N=numbers.length
DEMO
b4hand
9,5054 gold badges44 silver badges50 bronze badges
answered Apr 1, 2013 at 21:53
0
public class Practice {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
countUnique(list);
}
public static void countUnique(List<Integer> list){
Collections.sort(list);
Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
System.out.println(uniqueNumbers.size());
}
}
answered Jun 9, 2016 at 0:58
In JAVA8, you can simply use
stream()
and
distinct()
to get unique elements.
intArray = Arrays.stream(intArray).distinct().toArray();
answered Feb 6, 2019 at 18:49
Daniyal JavaidDaniyal Javaid
1,3872 gold badges17 silver badges32 bronze badges
1
There is an easier way to get a distinct list:
Integer[] intArray = {1,2,3,0,0,2,4,0,2,5,2};
List<Integer> intList = Arrays.asList(intArray); //To List
intList = new ArrayList<>(new LinkedHashSet<>(intList)); //Distinct
Collections.sort(intList); //Optional Sort
intArray = intList.toArray(new Integer[0]); //Back to array
Outputs:
1 2 3 0 0 2 4 0 2 5 2 //Array
1 2 3 0 0 2 4 0 2 5 2 //List
1 2 3 0 4 5 //Distinct List
0 1 2 3 4 5 //Distinct Sorted List
0 1 2 3 4 5 //Distinct Sorted Array
See jDoodle Example
answered Aug 7, 2019 at 7:17
PierrePierre
8,2574 gold badges63 silver badges79 bronze badges
You could do it like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
for (int n = 0; n < numbers.length; n++){
if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
store.add(numbers[n]);
}
}
numbers = new int[store.size()];
for (int n = 0; n < store.size(); n++){
numbers[n] = store.get(n);
}
Integer and int can be (almost) used interchangeably. This piece of code takes your array “numbers” and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store);
before numbers = new int[store.size()]
answered Apr 1, 2013 at 22:13
JustinJustin
23.9k12 gold badges92 silver badges141 bronze badges
I don’t know if you’ve solved your issue yet, but my code would be:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
int x = numbers.length;
int[] unique = new int[x];
int p = 0;
for(int i = 0; i < x; i++)
{
int temp = numbers[i];
int b = 0;
for(int y = 0; y < x; y++)
{
if(unique[y] != temp)
{
b++;
}
}
if(b == x)
{
unique[p] = temp;
p++;
}
}
for(int a = 0; a < p; a++)
{
System.out.print(unique[a]);
if(a < p-1)
{
System.out.print(", ");
}
}
b4hand
9,5054 gold badges44 silver badges50 bronze badges
answered Apr 4, 2013 at 21:06
String s1[]= {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
int c=0;
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
}
}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
c=0;
}
}
}
}
answered Jun 5, 2016 at 17:36
To find out unique data:
public class Uniquedata
{
public static void main(String[] args)
{
int c=0;
String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
s1[j]="";
}}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
s1[i]="";
c=0;
}
}
}
}
Misa Lazovic
2,8159 gold badges31 silver badges38 bronze badges
answered Jun 5, 2016 at 17:42
you can use
Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
SOFe
7,8304 gold badges32 silver badges60 bronze badges
answered Jan 10, 2017 at 19:50
2
Here is my piece of code using counting sort (partially)
Output is a sorted array consiting of unique elements
void findUniqueElementsInArray(int arr[]) {
int[] count = new int[256];
int outputArrayLength = 0;
for (int i = 0; i < arr.length; i++) {
if (count[arr[i]] < 1) {
count[arr[i]] = count[arr[i]] + 1;
outputArrayLength++;
}
}
for (int i = 1; i < 256; i++) {
count[i] = count[i] + count[i - 1];
}
int[] sortedArray = new int[outputArrayLength];
for (int i = 0; i < arr.length; i++) {
sortedArray[count[arr[i]] - 1] = arr[i];
}
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
Reference – discovered this solution while
trying to solve a problem from HackerEarth
answered Apr 19, 2017 at 10:03
ericdemo07ericdemo07
4618 silver badges16 bronze badges
If you are a Java programmer, I recommend you to use this.
It will work.
public class DistinctElementsInArray {
//Print all distinct elements in a given array without any duplication
public static void printDistinct(int arr[], int n) {
// Pick all elements one by one
for (int i = 0; i < n; i++) {
// Check if the picked element is already existed
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier, then print it
if (i == j)
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int array[] = { 4, 5, 9, 5, 4, 6, 6, 5, 4, 10, 6, 4, 5, 3, 8, 4, 8, 3 };
// 4 - 5 5 - 4 9 - 1 6 - 3 10 - 1 3 - 2 8 - 2
int arrayLength = array.length;
printDistinct(array, arrayLength);
}
}
keikai
13.7k8 gold badges47 silver badges67 bronze badges
answered Apr 30, 2020 at 10:36
1
public class DistinctArray {
public static void main(String[] args) {
int num[]={1,2,5,4,1,2,3,5};
for(int i =0;i<num.length;i++)
{
boolean isDistinct=false;
for(int j=0;j<i;j++)
{
if(num[j]==num[i])
{
isDistinct=true;
break;
}
}
if(!isDistinct)
{
System.out.print(num[i]+" ");
}
}
}
}
answered Mar 23, 2018 at 17:45
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
ArrayList in Java do not prevent the list from having duplicate values. But there are ways if you want to get unique values from the ArrayList and each way is explained with an example.
Method 1(Using Stream API’s distinct() Method): For Java 8, You can use Java 8 Stream API. To get distinct values, the distinct() method is an intermediate operation that also filters the stream to pass the next operation. Java Stream collect() is used to collect the stream elements to a collection (in this case a list).
Syntax:
Stream<T> distinct()
Return type: Stream is an interface and the function. It returns a stream consisting of distinct elements.
Java
import
java.util.*;
import
java.util.stream.Collectors;
public
class
Main {
public
static
void
main(String[] args)
{
ArrayList<Integer> Numbers
=
new
ArrayList<Integer>();
Numbers.add(
1
);
Numbers.add(
2
);
Numbers.add(
1
);
Numbers.add(
4
);
Numbers.add(
2
);
List<Integer> UniqueNumbers
= Numbers.stream().distinct().collect(
Collectors.toList());
System.out.println(
"Unique Values of ArrayList"
);
for
(
int
i =
0
; i < UniqueNumbers.size(); ++i) {
System.out.println(UniqueNumbers.get(i));
}
}
}
Output
Unique Values of ArrayList 1 2 4
Method 2(Using HashSet): One can convert the ArrayList to HashSet which does not allow duplicate values. For conversion, use the constructor of HashSet class which accepts Collection as an argument.
Java
import
java.util.ArrayList;
import
java.util.HashSet;
public
class
Main {
public
static
void
main(String[] args)
{
ArrayList<Integer> Numbers
=
new
ArrayList<Integer>();
Numbers.add(
1
);
Numbers.add(
2
);
Numbers.add(
1
);
Numbers.add(
4
);
Numbers.add(
2
);
HashSet<Integer> hashSetNumbers
=
new
HashSet<Integer>(Numbers);
System.out.println(
"Unique Values of ArrayList"
);
for
(Integer strNumber : hashSetNumbers)
System.out.println(strNumber);
}
}
Output
Unique Values of ArrayList 1 2 4
Maintaining order with no duplicate element’s insertion in the ArrayList.
LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Let us iterate through the elements in the order in which they were inserted. Following is the code that maintains insertion order and does not allow duplicate elements.
Java
import
java.util.*;
public
class
Main {
public
static
void
main(String[] args)
{
LinkedHashSet<Integer> UniqueList
=
new
LinkedHashSet<Integer>();
UniqueList.add(
1
);
UniqueList.add(
2
);
UniqueList.add(
3
);
UniqueList.add(
3
);
UniqueList.add(
2
);
List<Integer> ls
=
new
ArrayList<Integer>(UniqueList);
System.out.println(ls);
}
}
Method 4 : Using ArrayList ,add() and contains() method
Java
import
java.util.*;
public
class
Main {
public
static
void
main(String[] args)
{
List<Integer> ls =
new
ArrayList<Integer>();
ls.add(
1
);
ls.add(
2
);
ls.add(
1
);
ls.add(
4
);
ls.add(
5
);
List<Integer>ls1 =
new
ArrayList<Integer>();
for
(
int
i=
0
;i<ls.size();i++)
{
System.out.println(ls.get(i));
int
x;
if
(!ls1.contains(ls.get(i)))
{
x=ls.get(i);
ls1.add(x);
}
}
System.out.println(ls1);
}
}
Output
1 2 1 4 5 [1, 2, 4, 5]
Last Updated :
03 Nov, 2022
Like Article
Save Article
I’ve been trying to write code that finds the unique values in a sorted array that also has duplicates.
So far, I’ve written:
public static int numUnique (double[] list) {
int counter = 0;
if (Array.getLength(list) < 1) {
return Length.list);
}
else{
for (int i=0; i < Length.list); i++){
for (int j=i+1; j< Length.list); j++){
if (list[i] != list[j]){
newrArray[i] = list[i];
counter++;
}
}
}
}
return counter;
}
Input:
{31, 31, 31, 31, 33, 46, 46, 46, 46, 46, 52, 65, 65, 66, 75, 98, 98}
Expected output:
8
I cannot use HashSet
s or ArrayList
s. I think the only viable option is copying from one array to another and then counting what is in the new array (assuming that only unique values are copied into the new array).
Yu Hao
119k44 gold badges230 silver badges288 bronze badges
asked Jan 16, 2017 at 20:44
4
Do you know the maximum value in this array? If it’s small enough, you can make a boolean array of that size and set the value to true if you find that value in the original array.
This is called counting sort.
Example:
boolean[] found = new boolean[max];
for(int i : list)
found[i] = true;
int unique = 0;
for(int i = 0; i < found; i++)
if(found[i]) unique++;
If not, count the number of unique elements and insert them.
public int uniqueAmount(double[] list) {
double last = Double.NaN;
int unique = 0;
for(int i = 0; i < list.length; i++)
if(last != (last = list[i]))
unique++;
return unique;
}
public double[] uniqueValues(double[] list) {
int unique = uniqueAmount(list);
double[] found = new double[unique];
double last = Double.NaN;
last = list[0];
found[0] = last;
for(int i = 0, index = 1; i < list.length; i++)
if(last != list[i]) {
found[index++] = list[i];
last = list[i];
}
return found;
}
Tested and it works.
Returns 8 if you call uniqueAmount
and the array [31.0, 33.0, 46.0, 52.0, 65.0, 66.0, 75.0, 98.0]
if you call uniqueValues
(as requested in your edit).
answered Jan 16, 2017 at 20:48
SalemSalem
13.1k4 gold badges50 silver badges70 bronze badges
1
You can also use stream to do this. I create an IntStream in range from first index to last in the array. Then I filter elements using “indexOf(elem)” method that are first occurrances of numbers in the array. After that, using “mapToObj()” i can get appropriate elements and using “count()” get their amount.
For example:
List<Integer> d = Arrays.asList(31, 31, 31, 31, 33, 46, 46, 46, 46, 46, 52, 65, 65, 66, 75, 98, 98);
long result = IntStream.range(0, d.size())
.filter(a -> a == d.indexOf(d.get(a)))
.mapToObj(d::get)
.count();
System.out.println(result);
answered Jan 16, 2017 at 21:10
K.RzepeckaK.Rzepecka
3222 silver badges9 bronze badges
7
You’re overcomplicating things quite a bit:
Since the array is sorted, all you need to do is check whether a value and the value before it in the array are equal. If they aren’t increment the count, else continue with the next value:
int uniqueNum(double[] d){
if(d.length < 2)
return d.length;
int count = 0;
//choose an initial previous value that differs from the first element in the array
double prev = (d[0] == 1.0 ? 2.0 : 1.0);
for(double v : d){
//ignore duplicate values
if(v == prev)
continue;
count++;
prev = v;
}
return count;
}
This works since in a sorted array duplicate values will always form a sequence.
Why your code doesn’t work:
for (int i=0; i < Array.getLength(list); i++){
for (int j=i+1; j< Array.getLength(list); j++){
if (list[i] != list[j]){
catcherArray[i] = list[i];
counter++;
}
}
}
This codes doesn’t count the number of distinct values in the array, but for any index in the array the number of values that are different from the value at that index.
answered Jan 16, 2017 at 21:01
There is no need to copy any arrays or use extra data structures since you are given the array in sorted order. That means when list[i] != list[i+1] there won’t be any more occurrences in the array. This helps you greatly and allows you to do a single traverse of the array in order to find a solution. Here is the simple solution with no extra collections
public static int FindTotalUniqueNumbers(double[] list)
{
if(list.length < 0)
return 0;
double currentNumber = list[0];
int currentCount = 1;
for(int i = 1; i < list.length; i++)
{
if(list[i] != currentNumber)
{
currentCount++;
currentNumber = list[i];
}
}
return currentCount;
}
Example
double[] list = new double[] {31, 31, 31, 31, 33, 46, 46, 46, 46, 46, 52, 65, 65, 66, 75, 98, 98};
System.out.println(FindTotalUniqueNumbers(list));
Output
8
answered Jan 16, 2017 at 21:02
RAZ_Muh_TazRAZ_Muh_Taz
4,0191 gold badge12 silver badges26 bronze badges
0
The array is sorted, which means the duplicate values are next to each other. It’s good news for us because once we see a different value than the previous, we know for sure that the previous value is not going to show up again, ever. We can do a linear scan:
int countDistinct(double [] numbers) {
if (numbers == null || numbers.length == 0) return 0;
int c = 1, n = numbers.length;
// The previous value, initialized to the first element
double prev = numbers[0];
// Start loop from the second element
for (int i = 1; i < n; i++) {
if (prev != numbers[i]) {
c++;
prev = numbers[i];
}
}
return c;
}
answered Jan 16, 2017 at 21:37
xiaofeng.lixiaofeng.li
8,1172 gold badges23 silver badges30 bronze badges
Since this code snippet does not require you to sort the array, considering that the elements are sorted, a more efficient version of this can be written. However, this is efficient for unsorted arrays.
public static int numUnique(double[] list) {
double[] tempArray = new double[0];
int index;
for (double element : list) {
boolean matchFound = false;
if (tempArray.length > 0) {
for (double d : tempArray) {
if (d == element) {
matchFound = true;
break;
}
}
}
if (!matchFound) {
tempArray = Arrays.copyOf(tempArray, tempArray.length + 1);
tempArray[tempArray.length - 1] = element;
}
}
return tempArray.length;
}
answered Jan 16, 2017 at 21:58
2
You can you use IntStream distinct() or DoubleStream distinct() based on your array.
double[] doubleArray ={31.0, 31.0, 31.0, 31.0, 33.0, 46.0, 46.0, 46.0, 46.0, 46.0, 52.0, 65.0, 65.0, 66.0, 75.0, 98.0, 98.0};
long count = DoubleStream.of(doubleArray).distinct().count();
System.out.println(count);
Output:
8
If you have int array you can use IntStream distinct()
int[] intArray = {31, 31, 31, 31, 33, 46, 46, 46, 46, 46, 52, 65, 65, 66, 75, 98, 98};
long count = IntStream.of(intArray).distinct().count();
System.out.println(count);
Output:
8
answered Aug 11, 2017 at 9:40
soorapadmansoorapadman
4,4217 gold badges35 silver badges47 bronze badges
Чтобы получить отдельные значения в массиве в Java, вам нужно сравнить каждый элемент массива со всеми оставшимися элементами, в случае совпадения вы получите повторяющийся элемент. Одно из решений для этого – использовать два цикла (вложенных), где внутренний цикл начинается с i + 1 (где i – переменная внешнего цикла), чтобы избежать повторений в сравнении.
Пример
import java.util.Arrays; import java.util.Scanner; public class DetectDuplcate { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created::"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i=0; i<size; i++) { myArray[i] = sc.nextInt(); } System.out.println("The array created is ::"+Arrays.toString(myArray)); System.out.println("indices of the duplicate elements :: "); for(int i=0; i<myArray.length; i++) { for (int j=i+1; j<myArray.length; j++) { if(myArray[i] == myArray[j]) { System.out.println(j); } } } } }
Итог
Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 87 52 87 63 41 63 The array created is :: [87, 52, 87, 63, 41, 63] indices of the duplicate elements :: 2 5
In Java, an array is a collection of elements of the same data type. An array doesn’t restrict us from entering the same or repeated elements in it. So, many times we need to get the distinct elements from the array. In Java, there is more than one way to find unique elements from an array which are as follows:
- By storing all the elements to the hashmap’s key.
- By using nested loop.
- By using sorting.
- By using hashing.
By using hashmap’s key
In Java, the simplest way to get unique elements from the array is by putting all elements of the array into hashmap’s key and then print the keySet(). The hashmap contains only unique keys, so it will automatically remove that duplicate element from the hashmap keySet.
Let’s take an example to understand how the hashmap’s key is used to get the distinct element.
UniqueElementsExample1.java
Output
By using nested loop
Another simple approach to getting distinct elements from the given array is by using the nested loop. The inner and outermost loop plays a very important role in this strategy. The outermost loop takes an element one by one from the leftmost side of the array. The innermost loop compares it with the right-side of this element. If it matches, we skip it else, print or store it into another array that contains the distinct element.
Let’s take an example to understand how this strategy works in Java:
UniqueElementsExample2.java
Output
By using sorting
The solution we have discussed before has O(n2) time complexity, but we have another solution that has less complexity than the previous one. We can get the distinct elements from the array by performing a sorting algorithm. This solution has O(nLogn) time complexity.
In order to get the distinct element from the array, we will first sort the array in ascending or descending order so that each element’s occurrence becomes consecutive. After that, we will traverse that sorted array using the loop and skip all the consecutive repeated elements’ index.
Let’s take an example to understand how we can get the distinct element from the array by using the sorting algorithm.
UniqueElementsExample3.java
Output
By using hashing
There is another way to get the distinct element from the array, i.e., hashing. By using the hashing, we can get a distinct element in O(n). We traverse the array from which we want to get the distinct element. We perform traversing from left to right, and in the hash table, we keep the record of the visited element.
Let’s implement the code to understand how hashing is used to get the distinct element from the array.
UniqueElementsExample4.java
Output
All the above-discussed methods are used to get the distinct elements from the array. All the methods have different time complexity to get the distinct element. All the methods play an important role in different scenarios.