0
Sponsored Links


Ad by Google
This is again a very useful and frequently used in project and also very popular in core Java written interview question, not only in core Java but yes finding common elements between array is in any language always on demand.
We know that, array is something in any programming language which is really a powerful and day by day used in project. I think without array no project will complete, almost every project has array..

Lets compare two array to find the common elements, of course you can find out common elements with multiple ways and few of them are here listed in below program.
We have two array something like,
int [] array1 = [1,2,3,4,5,6];
int [] array2 = [8,1,3,9,4,5];
Expected output: 1,3,4,5

package com.javamakeuse.poc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 
 * @author javamakeuse
 *
 */
public class ArrayCompare {
 public static void compareArray(Integer[] array1, Integer[] array2) {

  for (int i = 0; i < array1.length; i++) {
   for (int j = 0; j < array2.length; j++) {
    if (array1[i] == array2[j]) {
     System.out.println(array1[i]);
    }
   }
  }
 }

 public static void compareArray2(Integer[] array1, Integer[] array2) {

  List<Integer> list1 = Arrays.asList(array1);
  List<Integer> list2 = Arrays.asList(array2);
  List<Integer> list3 = new ArrayList<>(list1);
  list3.retainAll(list2);
  System.out.println("list3 " + list3);
 }

 public static void main(String[] args) {
  Integer[] array1 = { 1, 2, 3, 4, 5, 6 };
  Integer[] array2 = { 8, 1, 3, 9, 4, 5 };
  compareArray(array1, array2);
  compareArray2(array1, array2);
 }
}

OUTPUT:
1
3
4
5
list3 [1, 3, 4, 5]

Sponsored Links
Next
This is the most recent post.
Older Post

0 comments:

Post a Comment