How to combine two list string into one list - java

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);

Related

Comparing two ArrayLists and remove duplicates from original ArrayList

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);

Error: generic array creation with my own object

I want to create a list that contains linked list of MyObject.
LinkedList<MyObject>[] list = new LinkedList<MyObject>[n];
But it shows:
Main.java:19: error: generic array creation LinkedList<MyObject>[] list = new LinkedList<MyObject>[n];
How can I create this kind of list?
Why are you trying to create an array of LinkedLists? it is after all already a List.
Change your code to
List <MyObject> list = new LinkedList<MyObject>();
if you want a collection of these LinkedLists then I suggest that you create a new List
List <LinkedList<MyObject>> theBigList = new ArrayList <> ();
and then you can add to this list
theBigList.add (list);
A List of Lists would look like:
List<List<MyObject>> listList = new LinkedList<>();
List<MyObject> list1 = new LinkedList<>();
List<MyObject> list2 = new LinkedList<>();
listList.add(list1);
listList.add(list2);
List<MyObject> list3 = listList.get(0);
And an Array of LinkedLists would look like:
#SuppressWarnings("unchecked")
List<MyObject>[] listArray = new LinkedList[n];
List<MyObject> list1 = new LinkedList<>();
List<MyObject> list2 = new LinkedList<>();
listArray[0] = list1;
listArray[1] = list2;
List<MyObject> list3 = listArray[0];
Both assume the diamond operator (<>) which is a Java 7 shortcut, but can be replaced with the full type (new LinkedList<MyObject> for the second and LinkedList<List<MyObject>> for the first case).
And the fact that arrays cannot be instantiated of generic type (due to all kinds of weird internals). See for example http://bugs.java.com/bugdatabase/view_bug.do?bug_id=5105887

Java sorting a String array and return the distinct Item

I have given the two arrays
array 1 : a, b, c, d
array 2 : a, b, c
I have used the
ArrayList<String> combine = new ArrayList<String> ()
and all the elements in array 1 and array 2
By sorting, I have found
a , a , b , b , c , c , d
Would you please tell me how to compare the elements in these two arrays and return the distinct items (d for example)?
Something like
ArrayList<String> charsA = new ArrayList<>();
charsA.addAll(Arrays.asList("a", "a", "b", "c", "d"));
ArrayList<String> charsB = new ArrayList<>();
charsB.addAll(Arrays.asList("a", "b", "c"));
charsA.removeAll(charsB);
System.out.println(charsA);
prints
[d]
Obviously use a different list if you don't want any of the two original to be affected.
The removeAll(Collection) method
Removes from this list all of its elements that are contained in the
specified collection.
If you want to do it with Arrays then you have to loop over both the arrays and compare values one by one. If you want to do it with ArraysLists then you can build your logic around contains() and remove() methods.
List<String> list1 = new ArrayList<String>();
list1.add("a");
list1.add("b");
list1.add("c");
list1.add("d");
List<String> list2 = new ArrayList<String>();
list2.add("a");
list2.add("b");
list2.add("c");
List<String> distinctList = new ArrayList<String>();
for (String string : list1) {
if (!list2.contains(string)) {
distinctList.add(string);
}
}

Remove Duplicates from Two Dimensional ArrayList

I have a two dimensional ArrayList that I need to filter the duplicates out of.
current result of generateRows: [["one"], ["two"], ["three"], ["one"]]
Java Pseudo Code:
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
rows = generateRows(); //method not shown, but returns a ArrayList<ArrayList<String>>
Set<String> set = new LinkedHashSet<String>();
for (ArrayList<String> list:rows) {
set.addAll (list);
}
rows.clear();
rows.add(new ArrayList<String>(set));
current result after running above conversion code: [[one, two, three]]
desired result: [["one"], ["two"], ["three"]]
Keeping code in same lines as what you have posted, here is what you have to do.
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
rows = generateRows(); //method not shown, but returns a ArrayList<ArrayList<String>>
Set<ArrayList<String>> set = new LinkedHashSet<ArrayList<String>>();
set.addAll(rows);
rows.clear();
rows.addAll(set);
Main issue with your routine:
Set<String> set = new LinkedHashSet<String>(); you are saying set is going to contain String types while your real set of objects to be unique is of ArrayList type
You can't store String values ("one", "two", "three") in a list which is supposed to store ArrayList<String> values.
To store the three strings, you'll need to create a new list of type ArrayList<String>.
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
rows = generateRows();
Set<String> set = new LinkedHashSet<String>();
for (ArrayList<String> list:rows) {
set.addAll (list);
}
//rows.clear();
//rows.add(new ArrayList<String>(set));
ArrayList<String> noDups = new ArrayList<String>(set);
Btw,
These lines...
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
rows = generateRows();
are equivalent to
ArrayList<ArrayList<String>> rows = generateRows();
You should prefer to program against interfaces instead of concrete classes, so if I were you I would write it as
List<List<String>> rows = generateRows();

Can I name an array with a variable in java? [duplicate]

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 3 years ago.
for example I want to do this:
String[] arraynames = new String[2];
arraynames[0] = "fruits";
arraynames[1] = "cars";
and now I don't know how to do this
String[] arraynames[0] = new String[100]; // ??????
so that I create a String array called fruits with 100 cells...
I know this doesn't work but is there someway to do this?
Use an HashMap
Example:
HashMap<String,String[]> arraynames = new HashMap<String,String[]>();
arraynames.put("fruits", new String[1000]);
// then simply access it with
arraynames.get("fruits")[0] = "fruit 1";
However, may I suggest you replace arrays with ArrayList ?
HashMap<String,ArrayList<String>> arraynames = new HashMap<String,ArrayList<String>>();
arraynames.put("fruits", new ArrayList<String>());
// then simply access it with
arraynames.get("fruits").add("fruit 1");
** EDIT **
To have an array of float values instead of strings
HashMap<String,ArrayList<Float>> arraynames = new HashMap<String,ArrayList<Float>>();
arraynames.put("fruits", new ArrayList<Float>());
// then simply access it with
arraynames.get("fruits").add(3.1415f);
So, you are looking for a doubly indexed array?
Something like:
String[][] arraynames = String[2][100];
You have created an array of 2 arrays that contain 100 String elements each in this case.
I hope I get you right, you could something like this:
ArrayList arraynames = new ArrayList();
arraynames.add("fruits");
arraynames.add("cars");
arraynames.set(0, new ArrayList(100) );
I am not quite clear on the second line of code here. You said you are trying to create a string array named fruits. This should suffice if I understood this right.
String [] fruits = new String[100];
you should use a bi-dimensional array like this:
String[][] myData = new String[2][100];
now myData is an array with 2 elements, both of them are arrays of "100 cells", then you can use these 2 arrays as follows:
String[] fruits = myData[0];
String[] cars = myData[1];
fruits[0] = "peach";
cars[0] = "mustang";
Using Guava library:
ListMultimap<String,String> mappedItems = ArrayListMultimap.create();
mappedItems.put("Fruits","Apple");
mappedItems.put("Fruits","Orange");
mappedItems.put("Fruits","Banana");
mappedItems.put("Cars", "BMW");
mappedItems.put("Cars","Ferrari");
System.out.println(mappedItems);
Output:
{Cars=[BMW, Ferrari], Fruits=[Apple, Orange, Banana]}
You can use one of the following :
String[][] arraynames = String[2][100];
Map<String, String[]> namesMap = new HashMap<String, String[]>();
List<List<String>> names = new ArrayList<ArrayList<String>()>>();

Categories