In: Computer Science
(Java Programming Problem)
Build two ArrayList lists from the Integer and String type arrays, populate the lists with repeats (see example below). Write a generic method (removeDuplicates( ….. )) to remove those duplicate items and returns an ArrayList<E> list without duplicates.
Original Integer List: [14, 24, 14, 42, 24, 25, 25, 23]
No-Duplicate List: [14, 24, 42, 25, 23]
Same generic method for the name list
Original List: [Mike, Lara, Jenny, Lara, Jared, Jonny, Lindsey, Mike, Jared]
No-Duplicate List: [Mike, Lara, Jenny, Jared, Jonny, Lindsey]
SOLUTION-
I have solve the problem in Java code with comments and screenshot
for easy understanding :)
CODE-
//java code
import java.util.ArrayList;
import java.util.Arrays;
//class
public class RemoveDuplicates {
//to remove duplicates
public static <E> ArrayList<E>
removeDuplicates(ArrayList<E> list) {
ArrayList<E> newList = new ArrayList<>();
for(int i = 0; i < list.size(); ++i)//find for duplicate in
array list
{
if(!newList.contains(list.get(i))) //if two same element is present
in array list
{
newList.add(list.get(i));
}
}
return newList; //return new list
}
public static void main(String[] args)
{
ArrayList<Integer> numbers = new
ArrayList<>(Arrays.asList(14, 24, 14, 42, 24, 25, 25, 23));
//given array list
System.out.println("original Integer list" + numbers); //print
given list
System.out.println("no-dup list " + removeDuplicates(numbers));
//print new list
//given name array list
ArrayList<String> names = new
ArrayList<>(Arrays.asList("Mike", "Lara", "Jenny", "Lara",
"Jared", "Jonny", "Lindsey", "Mike", "Jared"));
System.out.println("original list" + names); //print given
list
System.out.println("no-dup list" + removeDuplicates(names));
//print new list
}
}
SCREENSHOT-
OUTPUT -
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I
WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------