Reputation: 1
I've got the solution for my question but feel free to add more or shorten the code I made !
Here is the code I already developped:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input Array Length:"); // limit of array
int n=sc.nextInt();
System.out.println();
String arr[]=new String [n];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter elements:"); // elements of array
arr[i] = sc.next();
}
for (int i = 0; i < arr.length -1; i++) { // start loop
for (int j = i+1; j < arr.length; j++)
{
if( (arr[i].equals(arr[j]))) // condition to find duplicate
{
System.out.println("Duplicate Element is : "+arr[j]);
}
}
}
}
Upvotes: 0
Views: 91
Reputation: 1620
Well, if you are looking for more readable and elegant code, this snippet might help..
String[] myStringArray = { "A", "B", "C", "D", "E" , "A", "B", "A", "AC"};
List<String> allStr = Arrays.asList( myStringArray );
Set<String> duplicateStrings = allStr.stream()
.filter(i -> Collections.frequency(allStr, i) >1)
.collect(Collectors.toSet());
System.out.println(duplicateStrings);
Explanations [Needed As always :-) ]:
Collections.frequency()
to get the count of occurrence of the same objectSet
Hope it helps.
What may I look next?
Java Stream API for further reading.
Upvotes: 0
Reputation: 18255
One of possible solution, is to create a Map
, where key
is an unique items from the array, and value
- items' count:
Set<String> duplicates = Arrays.stream(arr)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
Upvotes: 1