In: Computer Science
Java:
How do I compare two lists for example:
List<A> listOne {a,b,c,d,e}
List<A> listTwo {a,d,e}
1. I am supposed to make sure that whatever that is in listTwo is in listOne even though there's more in listOne and there are repetitives in listTwo e.g {a,a,d,e} but it would still turn out true. But if listTwo is {a,b,d,f} it would return false.
2. Also, how can I make sure that in listTwo, there can be repetitives of any elements in listOne but it cannot appear consecutively. For example, listTwo {a,b,c,b,e} or {a,b,c,d,e,d} or {a} is valid but listTwo {a,b,c,a} or {a,a,b,c,d} is invalid.
I am supposed to throw an exception if listTwo is null or empty, if an element in listTwo is not in listOne, and if an element in listTwo appears twice or more consecutively (the start and end of the list are also considered consecutive) in an ordeer with at least two elements.
1)
import java.util.*;
public class ArrayListExample
{
public static void main(String[] args)
{
ArrayList<String> listOne = new
ArrayList<>(Arrays.asList("a", "b", "c", "d","e"));
ArrayList<String> listTwo = new
ArrayList<>(Arrays.asList("a", "d","e"));
Collections.sort(listOne);
Collections.sort(listTwo);
//Compare unequal lists example
boolean isEqual = listOne.equals(listTwo); //false
System.out.println(isEqual);
listTwo.add("a");
Collections.sort(listTwo);
System.out.println(listTwo);
//adding same element list 2
//Compare equals lists example
LinkedHashSet<String> hashSet = new
LinkedHashSet<>(listTwo);
ArrayList<String> listWithoutDuplicates = new
ArrayList<>(hashSet);
System.out.println(listWithoutDuplicates);
listWithoutDuplicates.add("f");
System.out.println(listWithoutDuplicates);
isEqual = listOne.equals(listWithoutDuplicates); //true
System.out.println(isEqual);
}
}
output
2)
import java.util.*;
public class ArrayListExample
{
public static void main(String[] args)
{
ArrayList<String> listOne = new
ArrayList<>(Arrays.asList("a", "b", "c", "d","e"));
ArrayList<String> listTwo = new
ArrayList<>(Arrays.asList("a", "d","e"));
Collections.sort(listOne);
Collections.sort(listTwo);
try
{
if( listTwo.isEmpty() ) || if(!listOne.equals(listTwo)) throws
Exception
System.out.println("listtwo is not null or emty");
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(listOne);
System.out.println(listTwo);
}
}