How to interleave lists - java

I have something in my mind which have been bothering me for quite a while now and hope I can get some kind souls to help... :D
Anyway, here's what I wanna do:
I do actually have a number of list, say
List<String> a = {"for testA1", "for testA2", "for testA3"};
List<String> b; = {"for testB1", "for testB2", "for testB3"};
List<String> c; = {"for testC1", "for testC2", "for testC3"};
And I have an array list of objects that I want to add these strings into, i.e.
List<ObjectA> thislist = new ArrayList<ObjectA>();
In my ObjectA class I have:
public class ObjectA{
String testA;
String testB;
String testC;
}
My final output should be:
List<ObjectA> -
testA1
testB1
testC1
testA2
testB2
testC2
testA3
testB3
testC3
How can I go about setting these Strings in my object from the given individual list?
Sorry for my bad English, I hope it's understandable.
I had this in mind but didn't quite understand.
My code was
List<String> aList = ....;
List<String> bList = ....;
List<String> cList = ....;
List<ObjectA> someList = new ArrayList<ObjectA>();
for(String a: aList){
ObjectA obj = new ObjectA();
obj.setTestA(a);
}
ListIterator litr = someList.listIterator();
while(litr.hasNext()) {
ObjectA element = (ObjectA) litr.next();
// I wanna loop List<String> bList and add element.setTestB but it doesn't work.
// This is what I wanna do...
}

Iterator<String> aIt = a.iterator();
Iterator<String> bIt = b.iterator();
Iterator<String> cIt = c.iterator();
List<ObjectA> thislist = new ArrayList<ObjectA>();
// assumes all the lists have the same size
while(aIt.hasNext())
{
Object A o = new ObjectA(aIt.next(), bIt.next(), cIt.next());
thisList.add(o);
}

// do all the assertions to check that the sizes are the same
if (a.size() != b.size() || a.size() != c.size()) {
throw new IllegalStatException("Wrong size");
}
List<ObjectA> objects = new ArrayList<ObjectA>();
for (int i = 0; i < a.size(); i++) {
String aStr = a.get(i);
String bStr = b.get(i);
String cStr = c.get(i);
ObjectA obj = new ObjectA(aStr, bStr, cStr);
objects.add(obj);
}
Comment below makes a good point - this could potentially be an O(n^2) solution in the case of a linked list (or any other list which has O(n) access time to access arbitrary elements)

Well, assuming you mapped object is of type
public class Triplet{
private final String jedi;
private final String sith;
private final String padawan;
public Triplet(String jedi, String sith, String padawan){
this.jedi = jedi;
this.sith = sith;
this.padawan = padawan;
}
}
We could define a mapping iterator:
public static class TripletIterator implements Iterator<Triplet>{
Iterator<String> jedis;
Iterator<String> siths;
Iterator<String> padawans;
public TripletIterator(List<String> jedis, List<String> sith, List<String> padawns){
this.jedis = jedis.iterator();
this.siths = sith.iterator();
this.padawans = padawns.iterator();
}
#Override
public boolean hasNext() {
return jedis.hasNext() && siths.hasNext() && padawans.hasNext();
}
#Override
public Triplet next() {
return new Triplet(jedis.next(), siths.next(), padawans.next());
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Then you could simply:
List<String> jedis = asList("Obiwan","Yoda","Luke");
List<String> siths = asList("Lord Sidious", "Darth Mul", "Darth Vader");
List<String> padawans = asList("Anakin", "Jarjar", "Poncho");
Iterator<Triplet> iter = new TripletIterator(jedis, siths, padawans);
while(iter.hasNext()){
Triplet t = iter.next();
System.out.println(t);
}

for(int i = 0; i < 3; i++) {
ObjectA oa = new ObjectA();
oa.testA = a[i];
oa.testB = b[i];
oa.testC = c[i];
thislist.Add(oa);
}

Related

Why TreeSet in java behaving like below?

ArrayList<String> a1=new ArrayList<String>();
a1.add("Item1");
a1.add("58584272");
a1.add("62930912");
ArrayList<String> a2=new ArrayList<String>();
a2.add("Item2");
a2.add("9425650");
a2.add("96088250");
ArrayList<String> a3=new ArrayList<String>();
a3.add("Item3");
a3.add("37469674");
a3.add("46363902");
ArrayList<String> a4=new ArrayList<String>();
a4.add("Item4");
a4.add("18666489");
a4.add("88046739");
List<List<String>> a5=new ArrayList<List<String>>();
a5.add(a1);
a5.add(a2);
a5.add(a3);
a5.add(a4);
TreeSet<List<String>> ts=new TreeSet<List<String>>(new mycomparator());
for(int i=0; i<=a.size()-1; i++){
ts.add(a5.get(i));
}
System.out.Println(ts); // Returns [[Item1, 58584272, 62930912]]
public class mycomparator implements Comparator{
static int order,paramenter=0;
#Override
public int compare(Object o1, Object o2) {
List<String> a1=(List<String>)o1;
List<String> a2=(List<String>)o1;
int b1=Integer.parseInt(a1.get(paramenter));
int b2=Integer.parseInt(a2.get(paramenter));
if(b1>b2){ return order==1?1:-1;}
else if (b1<b2){return order==1?-1:1;}
else{return 0;}
}
}
In the above code,I am trying to add objects to tree set,After adding all the elements when I try to print the treeset,only the first element get added.Why this is happening ?
Result --> [[Item1, 58584272, 62930912]]
Your code has so many problems:
Using raw Comparator instead of parametrized version.
Using wrong variable in the for loop.
Using static variables in the comparator.
On a side note, you should follow the Java naming conventions e.g. the class mycomparator should be named as MyComparator.
Given below is the code incorporating these comments:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
class MyComparator implements Comparator<List<String>> {
int order, paramenter;
MyComparator(int order, int paramenter) {
this.order = order;
this.paramenter = paramenter;
}
#Override
public int compare(List<String> o1, List<String> o2) {
int b1 = Integer.parseInt(o1.get(paramenter));
int b2 = Integer.parseInt(o2.get(paramenter));
if (b1 > b2) {
return order == 1 ? 1 : -1;
} else if (b1 < b2) {
return order == 1 ? -1 : 1;
} else {
return 0;
}
}
}
public class Main {
public static void main(String[] args) {
ArrayList<String> a1 = new ArrayList<String>();
a1.add("Item1");
a1.add("58584272");
a1.add("62930912");
ArrayList<String> a2 = new ArrayList<String>();
a2.add("Item2");
a2.add("9425650");
a2.add("96088250");
ArrayList<String> a3 = new ArrayList<String>();
a3.add("Item3");
a3.add("37469674");
a3.add("46363902");
ArrayList<String> a4 = new ArrayList<String>();
a4.add("Item4");
a4.add("18666489");
a4.add("88046739");
List<ArrayList<String>> a5 = new ArrayList<ArrayList<String>>();
a5.add(a1);
a5.add(a2);
a5.add(a3);
a5.add(a4);
TreeSet<List<String>> ts = new TreeSet<List<String>>(new MyComparator(0, 1));
for (int i = 0; i < a5.size(); i++) {
ts.add(a5.get(i));
}
System.out.println(ts);
}
}
Output:
[[Item1, 58584272, 62930912], [Item3, 37469674, 46363902], [Item4, 18666489, 88046739], [Item2, 9425650, 96088250]]
Note: I've just implemented your logic inside your compare method as it is. If you can tell me the exact requirement, I will update the code inside compare or you can update it yourself.
It is because of this code loop limit you use "i<=a.size()-1".
The "a" is never defined in your code, meaning size to be provided is zero, then you minus 1, so it will be less than zero.
That means this loop will only be triggered once.
for(int i=0; i<=a.size()-1; i++){
ts.add(a5.get(i));
}
You have implemented the comparator incorrectly. Check the following code:
List<String> a1 = new ArrayList<String>();
a1.add("Item1");
a1.add("58584272");
a1.add("62930912");
List<String> a2 = new ArrayList<String>();
a2.add("Item2");
a2.add("9425650");
a2.add("96088250");
List<String> a3 = new ArrayList<String>();
a3.add("Item3");
a3.add("37469674");
a3.add("46363902");
List<String> a4 = new ArrayList<String>();
a4.add("Item4");
a4.add("18666489");
a4.add("88046739");
List<List<String>> a = new ArrayList<List<String>>();
a.add(a1);
a.add(a2);
a.add(a3);
a.add(a4);
Comparator<List<String>> comparator = new Comparator<List<String>>() {
#Override
public int compare(List<String> a1, List<String> a2) {
String b1 = a1.get(0);
String b2 = a2.get(0);
return b1.compareTo(b2);
}
};
TreeSet<List<String>> ts = new TreeSet<List<String>>(comparator);
for (int i = 0; i <= a.size() - 1; i++) {
ts.add(a.get(i));
}
System.out.println(ts);

Is there a way to compare two objects in a List and combine their values that is most optimal?(Java)

Quick question. Suppose I have a function total (List list) and I have a MyObject class that have a String and an int displayed below and I want to compare two different object Strings in my total method. If they are the same, add the value on both of them. Otherwise, do nothing.
For example data is
{[Johanna, 200], [Jack, 205], [Johanna, 100], [Jack, 50]};
The output should look like
{[Johanna, 300], [Jack, 255]};
public static class MyObject {
int value;
String name;
public MyObject(String nm, int val)
{
name = nm;
value = val;
}
}
public void total(List<MyObject> list) {
List<MyObject> newList = new ArrayList<MyObject>();
Collections.sort(list);
Iterator<Order> ItrL = list.iterator();
int index = 0;
while(ItrL.hasNext())
{
MyObject compare = ItrL.next();
Iterator<MyObject> ItrR = list.listIterator(index);
index++;
while (cmp.name.equals(ItrR.next().name)))
newList.add(new MyObject(cmp.name, cmp.value + ItrR.value));
}
}
You can do summing and comparisons in parallel with no need to sort first using streams.
List<MyObject> newList = Arrays.asList(
new MyObject("Johanna", 200),
new MyObject("Jack", 205),
new MyObject("Johanna", 100),
new MyObject("Jack", 50)
);
Map<String,Integer> map =
newList.stream().parallel()
.collect(Collectors.groupingBy(mo -> mo.name,
Collectors.summingInt(mo -> mo.value)));
System.out.println("map = " + map);
There is no method that is "most optimal" as it depends on how big the data is. The problem seems suitable for map-reduce, but if you have like only 4 elements, then the overhead cost doesn't justify a real map reduce algorithm.
So anyway, here's one alternative that is pre-Java 8 (list doesn't need to be sorted first):
public static Map<String, Integer> total(List<MyObject> list) {
Map<String, Integer> result = new HashMap<String, Integer>();
for (MyObject myObject : list) {
Integer prevValue = result.get(myObject.name);
if (prevValue == null) {
result.put(myObject.name, myObject.value);
} else {
result.put(myObject.name, myObject.value + prevValue);
}
}
return result;
}
You can reduce from n^2 to n*(n/2) by using
for(int i = 0 ...
for(int j = i + 1 ...

How to find the differences from 2 ArrayLists of Strings?

I have 2 Strings:
A1=[Rettangolo, Quadrilatero, Rombo, Quadrato]
A2=[Rettangolo, Rettangolo, Rombo, Quadrato]
I want to obtain this: "I have found "Quadrilatero", instead of "Rettangolo" ".
If I use removeAll() or retainAll() it doesn't work because I have 2 instances of "Rettangolo".
In fact, if I use a1.containsAll(a2), I get true and I want false.
Thanks all for considering my request.
Use the remove method from ArrayList. It only removes the first occurance.
public static void main(String []args){
//Create ArrayLists
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
ArrayList<String> a1=new ArrayList(Arrays.asList(A1));
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
ArrayList<String> a2=new ArrayList(Arrays.asList(A2));
// Check ArrayLists
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
// Find difference
for( String s : a1)
a2.remove(s);
// Check difference
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
}
Result
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo, Rettangolo, Rombo, Quadrato]
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo]
These two classes might help. Let me know how I can improve this further.
Feel free to use the code below in your own work.
I must point out that the current code does not take care of repeated list elements.
import java.util.List;
public class ListDiff<T> {
private List<T> removed;
private List<T> added;
public ListDiff(List<T> removed, List<T> added) {
super();
this.removed = removed;
this.added = added;
}
public ListDiff() {
super();
}
public List<T> getRemoved() {
return removed;
}
public List<T> getAdded() {
return added;
}
}
Util class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ListUtil {
public static <T> ListDiff<T> diff(List<T> one, List<T> two) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
if (!two.contains(elementOne)) {
//element in one is removed from two
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
if (!one.contains(elementTwo)) {
//element in two is added.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static <T> ListDiff<T> diff(List<T> one, List<T> two, Comparator<T> comparator) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
boolean found = false;
//loop checks if element in one is found in two.
for (int j = 0; j < two.size(); j++) {
T elementTwo = two.get(j);
if (comparator.compare(elementOne, elementTwo) == 0) {
found = true;
break;
}
}
if (found == false) {
//element is not found in list two. it is removed.
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
boolean found = false;
//loop checks if element in two is found in one.
for (int j = 0; j < one.size(); j++) {
T elementOne = one.get(j);
if (comparator.compare(elementTwo, elementOne) == 0) {
found = true;
break;
}
}
if (found == false) {
//it means element has been added to list two.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static void main(String args[]) {
String[] arr1 = { "london", "newyork", "delhi", "singapore", "tokyo", "amsterdam" };
String[] arr2 = { "london", "newyork", "delhi", "singapore", "seoul", "bangalore", "oslo" };
ListDiff<String> ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2));
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2), new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}); //sample for using custom comparator
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
}
}
Here are three solutions.
An implementation that uses a remove method.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
List<String> temp = new ArrayList<String>(list1);
temp.removeAll(list2);
return temp.size() == 0;
}
A solution that sorts then compares.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
Collections.sort(list1);
Collections.sort(list2);
for (int i=0;i<list1.size();i++){
if (!list1.get(i).equals(list2.get(i)))
return false;
}
return true;
}
And, just for fun, you could do this by doing a word count difference between the two arrays. It wouldn't be the most efficient, but it works and possibly could be useful.
public static boolean same(List<String> list1, List<String> list2){
Map<String,Integer> counts = new HashMap<String,Integer>();
for (String str : list1){
Integer i = counts.get(str);
if (i==null)
counts.put(str, 1);
else
counts.put(str, i+1);
}
for (String str : list2){
Integer i = counts.get(str);
if (i==null)
return false; /// found an element that's not in the other
else
counts.put(str, i-1);
}
for (Entry<String,Integer> entry : counts.entrySet()){
if (entry.getValue() != 0)
return false;
}
return true;
}
This will find the intersection between two arrays for this specific case you have explained.
String[] A1 = { "Rettangolo", "Quadrilatero", "Rombo", "Quadrato" };
String[] A2 = { "Rettangolo", "Rettangolo", "Rombo", "Quadrato" };
ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(A1));
ArrayList<String> a2 = new ArrayList<String>(Arrays.asList(A2));
a1.removeAll(a2);
System.out.println("I have found " + a1);
I hope this will help you
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
set1.addAll(Arrays.asList(A1));
set2.addAll(Arrays.asList(A2));
set1.removeAll(set2);
System.out.println(set1);// ==> [Quadrilatero]

Get value (String) of ArrayList<ArrayList<String>>(); in Java

I know it's simple question, but in
ArrayList<ArrayList<String>> collection;
ArrayList<String> listOfSomething;
collection= new ArrayList<ArrayList<String>>();
listOfSomething = new ArrayList<String>();
listOfSomething.Add("first");
listOfSomething.Add("second");
collection.Add(listOfSomething);
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
I want to take String from ArrayList of ArrayList, and I don't know how to do that. For example I go
ArrayList<String> myList = collection.get(0);
String s = myList.get(0);
and it works! but:
Big update:
private List<S> valuesS;
private List<Z> valuesZ;
ArrayList<ArrayList<String>> listOfS;
ArrayList<String> listOfZ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Zdatasource = new ZDataSource(this);
Zdatasource.open();
valuesZ = Zdatasource.getAllZ();
Sdatasource = new SDataSource(this);
Sdatasource.open();
valuesS = Sdatasource.getAllS();
List<Map<String, String>> groupData
= new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData
= new ArrayList<List<Map<String, String>>>();
listOfS = new ArrayList<ArrayList<String>>();
listOfZ = new ArrayList<String>();
for (S i : valuesS) { // S is class
for (Z j : valuesZ) { // Z is class
if(j.getNumerS().equals(i.getNumerS())) {
listOfZ.add(j.getNumerZ());
}
else
{
//listOfZ.add("nothing");
}
}
listOfS.add(listOfZ);
if(!listOf.isEmpty()) listOfZ.clear();
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
try
{
ArrayList<String> myList = listOfS.get(groupPosition);
String s = myList.get(childPosition);
PrintToast("group "+Integer.toString(groupPosition)+", child "+Integer.toString(childPosition) + " , "+ s);
}
catch(Exception e)
{
Log.e("FS", e.toString());
}
return true;
}
return me java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
when I click on item which really should exist. I didn't show code which generate ListView, but I can tell you that my listOfS contains 3 items:
first is Null listOfZ, second listOfZ got 2 elements, third listOfZ got 1 element.
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething); save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
A cleaner way of iterating the lists is:
// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
for (String string : innerList) {
// do stuff with string
}
}
I have String array like this
We have to pass data through response.body.getdata and this data pass in constructor like this,
List taginnerData;
"data": [
"banana",
"apple",
"grapes",
"Pears",
"Mango",
"Cherry",
"Guava",
"TorontoVsMilwaukee_12Jan19"
]
String[] myArray = new String[taginnerData.size()];
for (int i = 0; i < taginnerData.size(); i++) {
myArray[i] = String.valueOf(taginnerData.get(i));
holder.tv_channel_name.setText("" +taginnerData.get(i));
//we get any value from here to set in adapter
}

Compare strings in two different arraylist (JAVA)

This is a pice of my code :
ArrayList<String> Alist= new ArrayList<String>();
ArrayList<String> Blist= new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
so i have two array list i want to compare all items and check if they are not equal and if they are to print out only the items that are not equal.
so i make something like this:
http://postimage.org/image/adxix2i13/
sorry for the image but i have somekind of bug when i post here a for looop.
and the result is :
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
i want to print only the 2 that are not equal in the example they are gsm and pc
not equals..:gsm
not equals..:pc
Don't use != to compare strings. Use the equals method :
if (! Blist.get(i).equals(Alist.get(j))
But this wouldn't probably fix your algorithmic problem (which isn't clear at all).
If what you want is know what items are the same at the same position, you could use a simple loop :
int sizeOfTheShortestList = Math.min(Alist.size(), Blist.size());
for (int i=0; i<sizeOfTheShortestList; i++) {
if (Blist.get(i).equals(Alist.get(i))) {
System.out.println("Equals..: " + Blist.get(i));
}
}
If you want to get items that are in both lists, use
for (int i = 0; i < Alist.size(); i++) {
if (Blist.contains(Alist.get(i))) {
System.out.println("Equals..: " + Alist.get(i));
}
}
You can use the RemoveAll(Collection c) on one of the lists, if you happen to know if one list always contains them all.
You could use the following code:
ArrayList<String> Alist = new ArrayList<String>();
ArrayList<String> Blist = new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
for (String a : Alist)
{
for (String b : Blist)
{
if (a.equals(b))
{
System.out.println("Equals " + a);
break;
}
}
}
Output is:
Equals gsm
Equals pc
right now your comparing each element to all of the other ones. Do something like
for (int i = 0; i < Alist.size(); i++) {
if (!Alist.get(i).equals(Blist.get(i)) {
// print what you want
}
}
Thats of course assuming both lists have the same length.
Rather than writing code to manually compare list elements you might consider using Apache Commons Collections.
import org.apache.commons.collections.CollectionUtils;
List listA = ...;
List listB = ...;
Collection intersection = CollectionUtils.intersection(listA, listB);
import java.util.HashSet;
public class CheckSet<T> extends HashSet<T>{
#Override
public boolean add(T e) {
if (contains(e)) {
remove(e);
return true;
} else {
return super.add(e);
}
}
}
Add all elements of both of your lists to a CheckSet intance, and at the end it will only contain the ones not equal.
Here is one way:
public static boolean compare(List<String> first, List<String> second) {
if (first==null && second==null) return true;
if (first!=null && second==null) return false;
if (first==null && second!=null) return false;
if ( first.size()!=second.size() ) return false;
HashMap<String, String> map = new HashMap<String, String>();
for (String str : first) {
map.put(str, str);
}
for (String str : second) {
if ( ! map.containsKey(str) ) {
return false;
}
}
return true;
}
public static void main(String args[] ) throws Exception {
List<String> arrayList1 = new ArrayList<String>();
arrayList1.add("a");
arrayList1.add("b");
arrayList1.add("c");
arrayList1.add("d");
List<String> arrayList2 = new ArrayList<String>();
arrayList2.add("a");
arrayList2.add("b");
arrayList2.add("c");
arrayList2.add("d");
boolean isEqual = false;
if(arrayList1.size() == arrayList2.size()){
List<String> arrayListTemp = new ArrayList<String>();
arrayListTemp.addAll(arrayList1);
arrayListTemp.addAll(arrayList2);
HashSet<Object> hashSet = new HashSet<Object>();
hashSet.addAll(arrayListTemp);
if(hashSet.size() == arrayList1.size() &&
hashSet.size() == arrayList2.size()){
isEqual = true;
}
}
System.out.println(isEqual);
}
we can compare two different size arrayList in java or Android as follow.
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
array1.add("1");
array1.add("2");
array1.add("3");
array1.add("4");
array1.add("5");
array1.add("6");
array1.add("7");
array1.add("8");
array2.add("1");
array2.add("2");
array2.add("3");
array2.add("4");
for (int i = 0; i < array1.size(); i++) {
for (int j=0;j<array2.size();j++) {
if (array1.get(i) == array2.get(j)) {
//if match do the needful
} else {
// if not match
}
}
}
import java.util.Arrays;
public class ExampleContains {
public static boolean EligibleState(String state){
String[] cities = new String[]{"Washington", "London", "Paris", "NewYork"};
boolean test = Arrays.asList(cities).contains(state)?true:false;
return test;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(EligibleState("London"));
}
}

Categories