In: Computer Science
In your latest home assignment, you were asked to write a generic method that returns an ArrayList that contains the non-duplicate elements from the original list. For this question, write a generic method that returns an ArrayList that contains the non-duplicate elements or the duplicate elements depending on the boolean argument (dup) setting.
If dup = false, return the list with the non-duplicates,
else return the list with the duplicated elements in the original list.
Please use the following two arrays for this question.
Integer[] nlist = { 0, 24, 25, 14, 25, 24, 42, 45, 42, 25};
String[] srt = {"Sam", "Bob", "Sue","Bob","Matt","Nick","Sue","Bob"};
Use the following static method (Array2Collection(….) to convert them to two corresponding ArrayLists ( 4 points)
public static <T> void Array2Collection(T a[], Collection<T> c) {
for (T x: a)
c.add(x);
}
Write codes to return an ArrayList <E>: if dup = false, return the list with the non-duplicates, else return with the duplicated element in the original list.
// 24 points for codes inside this method.
public static <E> ArrayList<E> Duplicates(ArrayList<E> list, boolean dup) {
// add codes here….
// 4 points for preparing the arrayList(s) from the two given arrays.
// 15 points for building the two arrayList of elements from the original list
// 5 points for returning the appropriate list based on the dup switch
}
Your client prgram should display this:
original list[0, 24, 25, 14, 25, 24, 14, 42, 45, 42, 25]
nodup list [0, 24, 25, 14, 42, 45]
dup list [25, 24, 14, 42, 25]
-------------
original list[Sam, Bob, Sue, Bob, Matt, Nick, Sue, Bob]
nodup list[Sam, Bob, Sue, Matt, Nick]
dup list[Bob, Sue, Bob]
Java Program:
import java.util.*;
class Main {
public static <T> void Array2Collection(T a[], Collection<T> c)
{
for (T x: a)
c.add(x);
}
public static <E> ArrayList<E> Duplicates(ArrayList<E> list, boolean dup)
{
ArrayList<E> d=new ArrayList<E>();
if(dup)
{
HashMap<E,Integer> m=new HashMap<E,Integer>();
for(E i:list)
{
m.put(i,m.getOrDefault(i,0)+1);
}
for(E i:list)
{
if(m.getOrDefault(i,0)>1)
{
if(m.getOrDefault(i,0)%2!=0)
{
d.add(i);
m.put(i,m.getOrDefault(i,0)-1);
}
else
{
m.put(i,m.getOrDefault(i,0)+1);
}
}
}
}
else
{
Set<E> s = new LinkedHashSet<E>(list);
d=new ArrayList<E>(s);
}
return d;
}
public static void main(String[] args) {
Integer[] nlist = { 0, 24, 25, 14, 25, 24,14, 42, 45, 42, 25};
String[] srt = {"Sam", "Bob", "Sue","Bob","Matt","Nick","Sue","Bob"};
ArrayList<Integer> li=new ArrayList<Integer>();
Array2Collection(nlist,li);
System.out.println("Original List "+li);
System.out.println("Nodup List "+Duplicates(li,false));
System.out.println("Dup List "+Duplicates(li,true));
System.out.println("------------------------");
ArrayList<String> ls=new ArrayList<String>();
Array2Collection(srt,ls);
System.out.println("Original List "+ls);
System.out.println("Nodup List "+Duplicates(ls,false));
System.out.println("Dup List "+Duplicates(ls,true));
}
}
Output: