'comparing two arrays and printing the inex of the first array [closed]
hi im new to java and i want to compare two arrays from user input
enter the number of values in array : 5
3 6 8 10 11
enter the number of values in array : 4
5 10 3 11
output
1 4 1 5
if element present in array 1 is also present in array 2, then print the index in array 1 if not ( in case of 5) , greatest values less than 5, then print its index
import java.io.*;
import java.util.*;
class GFG {
// function to create hashsets
// from arrays and find
// their common element
public static void FindCommonElements(int[] arr1,
int[] arr2)
{
// create hashsets
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
// Adding elements from array1
for (int i : arr1) {
set1.add(i);
}
// Adding elements from array2
for (int i : arr2) {
set2.add(i);
}
// use retainAll() method to
// find common elements
set1.retainAll(set2);
System.out.println("Common elements- " + set1);
}
// main method
public static void main(String[] args)
{
// create Array 1
int[] arr1
= { 3, 6, 8, 10, 11 };
// create Array 2
int[] arr2 = { 5, 10, 3, 11 };
// print Array 1
System.out.println("Array 1: "
+ Arrays.toString(arr1));
// print Array 2
System.out.println("Array 2: "
+ Arrays.toString(arr2));
FindCommonElements(arr1, arr2);
}
}
how can i find and print the index rather than the values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
