Array, remove duplication

This tutorial show when passed two arrays of names, it will return an array without duplication.

public class RemoveDuplicationTest {
  
  public static String[] removeDuplicate(String[] names1, String[] names2) {
     // implementation
  }

  public static void main(String[] args) {
     String[] name1 = new String[] {"John","Jack","Olivia"};
     String[] name2 = new String[] {"Olivia","Bob","John"};
		
     System.out.println(String.join(", ", RemoveDuplicationTest.removeDuplicate(name1, name2)));
  }
}

Approach 1:

public static String[] removeDuplicate(String[] names1, String[] names2) {
  List<String> list1 = new ArrayList<>(Arrays.asList(names1));
  list1.addAll(new ArrayList<>(Arrays.asList(names2)));

  List<String> result = list1.stream().distinct().collect(Collectors.toList());
		
  String[] arr = result.toArray(new String[result.size()]);
  return arr;
}

Approach 2:

public static String[] removeDuplicate(String[] names1, String[] names2) { 
  List<String> list1 = new ArrayList<>(Arrays.asList(names1));
  list1.addAll(new ArrayList<>(Arrays.asList(names2)));
		
  List<String> newList = new ArrayList<>();
		
  for (String text : list1 ) {
     if (!newList.contains(text)) {
        newList.add(text);
     }
  }
  return newList.toArray(new String[newList.size()]);
}

int array remove duplicate

public static int[] removeDuplicate(int[] numbers) {
		
   List<Integer> list = new ArrayList<>();
				
   for (Integer number : numbers ) {
      if (!list.contains(number)) {
	  list.add(number);
      }
   }
		  
   Integer[] intArr = list.toArray(new Integer[list.size()]);
   int[] result = new int[intArr.length];
   for (int i=0; i < intArr.length; i++) {
	result[i] = intArr[i];
   }
   return result;
}
Array, remove duplication

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.