

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to pull distinct values from an array in java?
To pull distinct values in an array you need to compare each element of the array to all the remaining elements, in case of a match you got your duplicate element. One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.
Example
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); } } } } }
Output
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
- Related Questions & Answers
- MongoDB query to pull multiple values from array
- How to pull even numbers from an array in MongoDB?
- Pull multiple objects from an array in MongoDB?
- Getting distinct values from object array in MongoDB?
- How to pull all elements from an array in MongoDB without any condition?
- How to pull value from array of ObjectIDs in MongoDB?
- Removing an array element from MongoDB collection using update() and $pull
- How to use MongoDB $pull to delete documents within an Array?
- MongoDB query to pull array element from a collection?
- How to remove false values from an array in JavaScript?
- Get the length of distinct values in an array with MongoDB
- How to pull an array element (which is a document) in MongoDB?
- How to create an ArrayList from an Array in Java?
- How to remove an element from an array in Java
- MYSQL select DISTINCT values from two columns?
Advertisements