Comparing two ArrayLists and remove duplicates from original ArrayList - java

I have two Custom Arraylist:
List<Item> before = new ArrayList<Item>();
List<ItemEx> after = new ArrayList<ItemEx>();
before.add(new Item(1L,"test1"));
before.add(new Item(2L,"test2"));
before.add(new Item(3L,"test3"));
after.add(new ItemEx(1L,"test4"));
after.add(new ItemEx(2L,"test5"));
after.add(new ItemEx(4L,"test6"));
after.add(new ItemEx(5L,"test7"));
I want to store the elements in the List<ItemEx> after and the element shoulds be after the removing of common element is {3L, 4L, 5L}.

FYI
List<Item> & List<ItemEx> should be SAME TYPE .
Logic
List<String> before = new ArrayList<String>();
List<String> after = new ArrayList<String>();
List<String> list_checking = new ArrayList<String>(before);
list_checking.addAll(after);
List<String> list_common = new ArrayList<String>(before);
list_common.retainAll(after);
list_checking.removeAll(list_common);

Try this :
HashSet hs = new HashSet();
hs.addAll(before);
hs.addAll(after);
after.clear();
after.addAll(hs);
Now, in after list you get desire values.

Its simple. Take a copy of the existing one into a temporary Variable if you want for future use.
ArrayList temporiginalArrList=OriginalArrayList;
//here 'T' can be a specific object to want to save
OriginalArrayList.removeAll(secondArrayList);

Related

how to remove duplicate Element from Arraylist in java

{ "744101", "744101","744101", "744102",744102","744102","744102","744102","744103","744103"}
List<String> list2=new new ArrayList<String>(); //
Arrays.sort(iArr);
for(int k=0;k<iArr.length;k++) {
list2.add(String.valueOf(iArr[k]));
}
List li2 = new Array List(new HashSet(list2));
I'm unable to get result while trying to Sort Array list. Please correct me.
The TreeSet both sorts the elements and removes the duplicates.
String[] array = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};
List<String> list = new ArrayList<>(new TreeSet<>(Arrays.asList(array)));
list.forEach((element)->{
System.out.println(element);
});
Try this:
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
hash.addAll(list);
list.clear();
list.addAll(hash);
And than sort list if you want.
As Eran mentioned, you current implementation "shuffles" the list due to HashSet implementation being used, as this Set implementation doesn't retain the order. Try using LinkedHashSet instead. As mentioned in javadoc it avoids overheads related to TreeSet.
Code would be something like this
String[] arrayToProcess = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};
//creates array and sorts the list
List<String> sortedList = Arrays.asList(arrayToProcess);
Collections.sort(sortedList);
//removes duplicates the list, while retaining order of sorted list
Set<String> uniqueNumbers = new LinkedHashSet<String>();
uniqueNumbers.addAll(sortedList);
Note the implementation of Set being used is LinkedHashSet. Also this snippet makes two copies of the array so if array size is huge, I wouldn't suggest using it.
I would suggest you look up the implementations of collections in java. Because each of them has their own strengths and weaknesses:

How to replace one arraylist to another with different size in java

I have two array list with different size. How to Replace from this:
ArrayList<String> s = new ArrayList<String>();
ArrayList<String> f = new ArrayList<String>();
s.add("Nepal");
s.add("Korea");
s.add("Sri Lanka");
s.add("India");
s.add("Pakistan");
s.add("China");
s.add("Australia");
s.add("Bhutan");
f.add("London");
f.add("New York");
f.add("Mumbai");
f.add("sydeny");
for(int i=0;i<s.size();i++){
// Collections.copy(f, s);
f.addAll(s);
Log.d("TAG", "Sources---" + s.get(i));
Log.d("TAG", "Dest---" + f.get(i));
}
I have try both this. but not replace only append or copy from the existing array list.
My aim is totally replace original array to new arraylist.
You may do clear() first and then do addAll(s);
After clear() your arraylist will be empty.
EDIT:
As #Luggi commented, clear() will not be good option if list is big, instead simply point your f reference to new ArrayList with collection as parameter:
Example:
f = new ArrayList(s);
enter link description hereenter link description hereYou can do this in many ways
First clear then add all
f.clear();
f.addAll(S);
By first way all element copy from one list to another list if you want that both the list are same and manipulation in one list reflects in another list then you can point both on the same list like
f = s;
By intializing new list by adding all element into a new list.
f = new ArrayList(s);
ArrayList<String> s = new ArrayList<String>();
ArrayList<String> f = new ArrayList<String>();
s.add("Nepal");
s.add("Korea");
s.add("Sri Lanka");
s.add("India");
s.add("Pakistan");
s.add("China");
s.add("Australia");
s.add("Bhutan");
f.add("London");
f.add("New York");
f.add("Mumbai");
f.add("sydeny");
f.clear();
f.addAll(s);
If you want to add elements in f to s following will work
s.addAll(f);
That's all. Why you use for loop in your code?
You can try this out:
First add all elements from s to f
f.addAll(s);
Then retain only elements in f that are present in s
f.retainAll(s);

How to combine two list string into one list

I have two list string different,
List<String> A= [1,2,3,4];
List<String> B= [1,2,5,6];
And I want to combine two list, in new list string in
List C = new Arraylist ();
how to combine two list string , be like the example:
C = [1,2,3,4,5,6];
Use Collection.addAll(), and a TreeSet, to remove duplicates and keep the result sorted.
Set<String> c = new TreeSet<String>(a); //create a Set with all the elements in a
c.addAll(b); //add all the elements in b
This will get them combined
combined = new ArrayList<String>();
combined.addAll(A);
combined.addAll(B);
This will get the uniques
List<String> uniques = new ArrayList<String>(new HashSet<String>(combined));
Do it like this :
listOne.removeAll(listTwo);
listTwo.addAll(listOne);
Collections.sort(listTwo);
You can remove the third line if you do not want it to be sorted.
Declaration of A and B seems to be wrong.
However, given two lists A and B, to combine them into C, you can use the following code:
C.addAll(A);
C.addAll(B);
Set<String> set = new TreeSet<String>(A); // for keeping the output sorted else you can also use java.util.HashSet
set.addAll(B);
List<String> finalList = new ArrayList<String>(set);
There are two ways to merge the results of both lists: using List#addAll or Set#addAll. The main difference between both is heavily explained here: What is the difference between Set and List?
Based on your request, you should merge both lists without repeating the items using a Set
List<String> lstA = new ArrayList<String>();
lstA.add("1");
lstA.add("2");
lstA.add("3");
lstA.add("4");
List<String> lstB = new ArrayList<String>();
lstA.add("1");
lstA.add("2");
lstA.add("5");
lstA.add("6");
Set<String> lstC = new LinkedHashSet<String>();
lstC.addAll(A);
lstC.addAll(B);
List<String> lstAB = new ArrayList(lstC);
List<String> A= new ArrayList<String>();
List<String> B= new ArrayList<String>();
Set<String> set = new TreeSet<String>(A);
set.addAll(B);
System.out.println(new ArrayList<String>(set));
To get a List<String> in sorted order, use this piece of code
String a[] = {"1","2","3","4"};
String b[] = {"1","2","5","6"};
List<String> A= Arrays.asList(a);
List<String> B= Arrays.asList(b);
Set<String> CTemp = new TreeSet<>();
CTemp.addAll(A);
CTemp.addAll(B);
List<String> C = new ArrayList<>(CTemp);

How do I copy the contents of one ArrayList into another?

I have some data structures, and I would like to use one as a temporary, and another as not temporary.
ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();
//fill myTempObject here
....
//make myObject contain the same values as myTempObject
myObject = myTempObject;
//free up memory by clearing myTempObject
myTempObject.clear();
now the problem with this of course is that myObject is really just pointing to myTempObject, and so once myTempObject is cleared, so is myObject.
How do I retain the values from myTempObject in myObject using java?
You can use such trick:
myObject = new ArrayList<Object>(myTempObject);
or use
myObject = (ArrayList<Object>)myTempObject.clone();
You can get some information about clone() method here
But you should remember, that all these ways will give you a copy of your List, not all of its elements. So if you change one of the elements in your copied List, it will also be changed in your original List.
originalArrayList.addAll(copyArrayList);
Please Note: When using the addAll() method to copy, the contents of both the array lists (originalArrayList and copyArrayList) refer to the same objects or contents. So if you modify any one of them the other will also reflect the same change.
If you don't wan't this then you need to copy each element from the originalArrayList to the copyArrayList, like using a for or while loop.
There are no implicit copies made in java via the assignment operator. Variables contain a reference value (pointer) and when you use = you're only coping that value.
In order to preserve the contents of myTempObject you would need to make a copy of it.
This can be done by creating a new ArrayList using the constructor that takes another ArrayList:
ArrayList<Object> myObject = new ArrayList<Object>(myTempObject);
Edit: As Bohemian points out in the comments below, is this what you're asking? By doing the above, both ArrayLists (myTempObject and myObject) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained in myTempObject then you would need to make a copy of each individual object in the original ArrayList
Came across this while facing the same issue myself.
Saying arraylist1 = arraylist2 sets them both to point at the same place so if you alter either the data alters and thus both lists always stay the same.
To copy values into an independent list I just used foreach to copy the contents:
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
fill list1 in whatever way you currently are.
foreach(<type> obj in list1)
{
list2.Add(obj);
}
Supopose you want to copy oldList into a new ArrayList object called newList
ArrayList<Object> newList = new ArrayList<>() ;
for (int i = 0 ; i<oldList.size();i++){
newList.add(oldList.get(i)) ;
}
These two lists are indepedant, changes to one are not reflected to the other one.
Lets try the example
ArrayList<String> firstArrayList = new ArrayList<>();
firstArrayList.add("One");
firstArrayList.add("Two");
firstArrayList.add("Three");
firstArrayList.add("Four");
firstArrayList.add("Five");
firstArrayList.add("Six");
//copy array list content into another array list
ArrayList<String> secondArrayList=new ArrayList<>();
secondArrayList.addAll(firstArrayList);
//print all the content of array list
Iterator itr = secondArrayList.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
In print output as below
One
Two
Three
Four
Five
Six
We can also do by using clone() method for which is used to create exact copy
for that try you can try as like
**ArrayList<String>secondArrayList = (ArrayList<String>) firstArrayList.clone();**
And then print by using iterator
**Iterator itr = secondArrayList.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}**
You need to clone() the individual object. Constructor and other methods perform shallow copy. You may try Collections.copy method.
Straightforward way to make deep copy of original list is to add all element from one list to another list.
ArrayList<Object> originalList = new ArrayList<Object>();
ArrayList<Object> duplicateList = new ArrayList<Object>();
for(Object o : originalList) {
duplicateList.add(o);
}
Now If you make any changes to originalList it will not impact duplicateList.
to copy one list into the other list, u can use the method called
Collection.copy(myObject myTempObject).now after executing these line of code u can see all the list values in the myObject.
Copy of one list into second is quite simple , you can do that as below:-
ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);
Here is a workaround to copy all the objects from one arrayList to another:
ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();
myObject.addAll(myTempObject.subList(0, myTempObject.size()));
subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.
Suppose you have two arraylist of String type .
Like
ArrayList<String> firstArrayList ;//This array list is not having any data.
ArrayList<String> secondArrayList = new ArrayList<>();//Having some data.
Now we have to copy the data of second array to first arraylist like this,
firstArrayList = new ArrayList<>(secondArrayList );
Done!!
The simplest way is:
ArrayList<Object> myObject = new ArrayList<Object>();
// fill up data here
ArrayList<Object> myTempObject = new ArrayList(myObject);

How to make a Collection<String> object from comma separated values

I have a String object like
final String demoString = "1,2,19,12";
Now I want to create a Collection<String> from it. How can I do that?
Guava:
List<String> it = Splitter.on(',').splitToList(demoString);
Standard JDK:
List<String> list = Arrays.asList(demoString.split(","))
Commons / Lang:
List<String> list = Arrays.asList(StringUtils.split(demoString, ","));
Note that you can't add or remove Elements from a List created by Arrays.asList, since the List is backed by the supplied array and arrays can't be resized. If you need to add or remove elements, you need to do this:
// This applies to all examples above
List<String> list = new ArrayList<String>(Arrays.asList( /*etc */ ))
Simple and good,
List<String> list = Arrays.asList(string.split(","))
you can create a List<String> and assign it to Collection<String> as List extends Collection.
final String demoString = "1,2,19,12";
Collection<String> collection = List.of(demoString.split(","));

Categories