You are on page 1of 5

9/3/2015 How to get distinct elements from an array by avoiding duplicate elements?

 ­ Java Interview Programs

java example
programs

Home program: how to get dıstınct elements from an


Fundamentals
array by avoıdıng duplıcate elements?
Constructors Description:

Exception Handling The below example shows how to avoid duplicate elements from an array and disply only distinct
elements. Please use only arrays to process it.
Threads

String Functions Code:

package com.java2novice.algos;
Generics
public class MyDisticntElements {
Collections & Util Package
public static void printDistinctElements(int[] arr){
Nested Classes
for(int i=0;i<arr.length;i++){
Networking boolean isDistinct = false;
for(int j=0;j<i;j++){ Java Sample Progr
7,325 likes
File I/O Operations
if(arr[i] == arr[j]){
isDistinct = true;
break;
Java Annotations }
} Like Page
JDBC Examples if(!isDistinct){
System.out.print(arr[i]+" ");
} Be the first of your friends to like thi
Spring Core
}
}
Java Interview Questions
public static void main(String a[]){
Java Interview Programs
int[] nums = {5,2,7,2,4,7,8,2,3};
Java Restful Web Services MyDisticntElements.printDistinctElements(nums);
}
JSON in Java }

JUnit
Output:
Java Design Patterns
527483
Search Algorithms

Sorting Algorithms
<< Previous Program | Next Program >>
Data Structures

Gradle Configurations

JBoss Configurations

Java Issues

22 Comments JAVA EXAMPLE PROGRAMS 
1  Login

  Recommend  3 ⤤ Share Sort by Best

Join the discussion…

Riz  •  a year ago
I got asked this question in the Interview... he then asked wht if you have millions of entries in the
array wht will you do then .... wht should have been my answer .... any suggestions.... thanx
8 △   ▽ • Reply • Share › 
Knowledge Centre
pumku > Riz  •  a year ago wait Vs sleep methods
//Hi, just do this
sleep(): It is a static method on Th
Integer[] array = { ­5, ­3, 6, 6, 8, 9, 69, 10, 10, 12, 12 }; makes the current thread into the
Set<integer> removedDuplicated = new HashSet<integer>(Arrays.asList(array)); Runnable" state for specified amou
During this time, the thread
(monitors) it has acquired.
//test
http://www.java2novice.com/java­interview­programs/distinct­elements/ 1/5
9/3/2015 How to get distinct elements from an array by avoiding duplicate elements? ­ Java Interview Programs
//test
for (Integer integer : removedDuplicated) { wait(): It is a method on Object cla
System.err.println(integer); the current thread into the "Not Ru
state. Wait is called on a object, n
} Before calling wait() method, the
1 △   ▽ • Reply • Share ›  be synchronized, means the object
inside synchronized block.
releases the acquired lock.
Nitin Pachori > pumku  •  a year ago
If interviewer asks again in same he wants duplicate numbers to print then yours will
fail.
△  ▽ • Reply • Share › 

Nilesh > Nitin Pachori  •  a month ago
Or you can use Map instead set.
△  ▽ • Reply • Share › 

rose  •  a year ago
The above code is incorrect. It does not work for this array {5,2,7,2,4,7,8,2,3,1,5}
1 △   ▽ • Reply • Share › 

Totsie  •  a year ago
This is O(n2).

I recommend to sort (say, using mergesort), then iterate over the sorted array. If an element is
repeated, do not print it.
1 △   ▽ • Reply • Share › 

dev1 > Totsie  •  10 months ago
sorting then iterating would be O(n2logn) which would be even worse
△  ▽ • Reply • Share › 

hanu > Totsie  •  a year ago
give the explanation for every exampl plz.....................it useful for more people
△  ▽ • Reply • Share › 

Sandeep  •  3 months ago
I just used to set's for holding distinct and duplicate elements.

import java.util.HashSet;

import java.util.Set;

class TestClass1 {

public static void main(String args[] ) {

Set<integer> distinctElements=new HashSet<integer>();

Set<integer> duplicateElements=new HashSet<integer>();

int [] array={1,1,1,2,2,3,4,4,5,6} ;

for (int currentElement : array) {

if(duplicateElements.contains(currentElement)){

}
see more

△  ▽ • Reply • Share › 

Arjuna  •  3 months ago
Program to print duplicate numbers and distinct numbers:

public class DuplicateAndDistinctNumbers {

public static void main(String[] args) {

int[] numbers = new int[]{5,2,7,2,4,7,8,2,3};

printDuplicateAndDistinctNumbers(numbers);

private static void printDuplicateAndDistinctNumbers(int[] numbers){

HashMap<integer, boolean=""> dupNumbers = new HashMap<integer, boolean="">();
http://www.java2novice.com/java­interview­programs/distinct­elements/ 2/5
9/3/2015 How to get distinct elements from an array by avoiding duplicate elements? ­ Java Interview Programs
HashMap<integer, boolean=""> dupNumbers = new HashMap<integer, boolean="">();

for(int i : numbers){

if(dupNumbers.get(i) != null){

dupNumbers.put(i, true);
see more

△  ▽ • Reply • Share › 

Anny  •  4 months ago
I mean What is the asymptotic worst­case complexity of the algorithm?
△  ▽ • Reply • Share › 

Anny  •  4 months ago
What is the running time of this algorithm?
△  ▽ • Reply • Share › 

gautam kumar  •  5 months ago
whatever code is showing above, it is not giving correct answer

Correct code is::

/**

*/
package com.gtm.interview;

/**
* @author kumarga
*
*/
public class DistinctElements {

public static void printDistinctElements(int[] arr){
//int arr[]=sortArray(arr1);
for (int i = 0; i < arr.length; i++) {
boolean isDistinct=false;
see more

△  ▽ • Reply • Share › 

Tanmay Durgule  •  6 months ago
public class ShowDistinctElementFromAnArray {
static boolean isNotDistinct=false;
public static void FindDistinct(int a[]){
for(int i=0;i<a.length;i++){ isnotdistinct="false;" for(int="" j="i;j&lt;a.length;j++){" if(j!="i){" if(a[i]="=a[j]){"
isnotdistinct="true;" }="" }="" }="" if(!isnotdistinct){="" system.out.print("="" "+a[i]);="" }="" }="" }=""
public="" static="" void="" main(string[]="" args)="" {="" scanner="" sc="new" scanner(system.in);=""
system.out.println("enter="" the="" size="" of="" array:="" ");="" int="" size="sc.nextInt();" if(size="">0)
{
int a[]=new int[size];
System.out.println("Enter The Elements of Array: ");
for(int i=0;i<a.length;i++){ a[i]="sc.nextInt();//5,2,7,2,4,7,8,2,3,1,5" }="" finddistinct(a);="" }else{=""
system.out.println("enter="" proper="" size="" please");="" }="" }="" }="">
△  ▽ • Reply • Share › 

shaikh salman  •  10 months ago
import java.util.*;

class SetDemo {

public static void main(String args[]) {

int count[] = {34, 22,10,60,10,22};

Set<integer> set = new HashSet<integer>();

try{

for(int i = 0; i<5; i++){

set.add(count[i]);

}
http://www.java2novice.com/java­interview­programs/distinct­elements/ 3/5
9/3/2015 How to get distinct elements from an array by avoiding duplicate elements? ­ Java Interview Programs
}

System.out.println(set);

TreeSet sortedSet = new TreeSet<integer>(set);
see more

△  ▽ • Reply • Share › 

Rax Haidvard  •  a year ago
i got a program to check whether a pair of Number is Amicable Number or Not . unfortunately my
logic failed . anyone can try this....
△  ▽ • Reply • Share › 

Derick Daniel > Rax Haidvard  •  6 months ago
public class AmicableNo {

public static void main(String[] args) {

for(int i=1;i<=2000;i++)

if(isAmicable(i)){

System.out.println(i+" is an amicable number.");

System.out.println();

static int returnAmicable(int no){

int result=0;

for(int i=1;i<=no/2;i++){
see more

△  ▽ • Reply • Share › 

Liz Tejada  •  a year ago
Really nice apport. It totally work out for me :)
△  ▽ • Reply • Share › 

hanu  •  a year ago
where is the explanantion...............................
△  ▽ • Reply • Share › 

ManuelMatz  •  a year ago
in the public class: MyDisticntElements there's a mispelling should be say 
MyDistinctElements
△  ▽ • Reply • Share › 

chiru  •  a year ago
nice answer Totsie
△  ▽ • Reply • Share › 

fitria alfiana  •  a year ago
i've tried those code, and when i tried to manipulated it using array 2D those code doesn't work. Nb :
i've put one extra looping and the result was false. help me please >.< (i'm sorry if my english was
bad)
△  ▽ • Reply • Share › 

✉ Subscribe d Add Disqus to your site ὑ Privacy

blog comments powered by Disqus

lıst of all ıntervıew programs:

Find out duplicate number between 1 to N numbers.

Find out middle index where sum of both ends are equal.

Write a singleton class.

http://www.java2novice.com/java­interview­programs/distinct­elements/ 4/5
9/3/2015 How to get distinct elements from an array by avoiding duplicate elements? ­ Java Interview Programs

Write a program to create deadlock between two threads.

Write a program to reverse a string using recursive algorithm.

Write a program to reverse a number.

Write a program to convert decimal number to binary format.

Write a program to find perfect number or not.

Write a program to implement ArrayList.

Write a program to find maximum repeated words from a file.

Wrie a program to find out duplicate characters in a string.

Write a program to find top two maximum numbers in a array.

Write a program to sort a map by value.

Write a program to find common elements between two arrays.

How to swap two numbers without using temporary variable?

Write a program to print fibonacci series.

Write a program to find sum of each digit in the given number using recursion.

Write a program to check the given number is a prime number or not?

Write a program to find the given number is Armstrong number or not?

Write a program to convert binary to decimal number.

Write a program to check the given number is binary number or not?

Write a program for Bubble Sort in java.

Write a program for Insertion Sort in java.

Write a program to implement hashcode and equals.

How to get distinct elements from an array by avoiding duplicate elements?

Write a program to get distinct word list from the given file.

Write a program to get a line with max word count from the given file.

Write a program to convert string to number without using Integer.parseInt() method.

Write a program to find two lines with max characters in descending order.

Write a program to find the sum of the first 1000 prime numbers.

Find longest substring without repeating characters.

Write a program to remove duplicates from sorted array.

How to sort a Stack using a temporary Stack?

About Author Most Visited Pages Other Interesting Sites

Java Interview Questions Techie Park


I'm Nataraja Gootooru, programmer by profession and passionate

about technologies. All examples given here are as simple as How to Create Java Custom Exception QA2QE

possible to help beginners. The source code is compiled and Java Interview Programs Wikipedia

tested in my dev environment. Java StringTokenizer With Multiple De‐limiters Sample Code Prashdeep

Java Constructor Chaining Examples query2nataraj.blogspot.in


If you come across any mistakes or bugs, please email me to

java2novice@gmail.com or you can comment on the page. Spring Framework Examples

Write a program to find maximum repeated words from a file.

Java Data Structures

Reference: Java™ Platform Standard Ed. 7 ­ API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2015 by Nataraja Gootooru. All Rights Reserved.

http://www.java2novice.com/java­interview­programs/distinct­elements/ 5/5

You might also like