Is there a way to put contents of mulitple Lists to a Set? (Eliminating the duplicates)
For example contents of listA, listB, listC all be put in a Set. (Assuming they are of same type)
You certainly can.
The Set will add all of the elements from each of the lists and then remove any duplicate objects based on the objects equals and hashCode() methods. (When implementing one, you should implement the other.)
List<Object> listA = new ArrayList<Object>();
List<Object> listB = new ArrayList<Object>();
List<Object> listC = new ArrayList<Object>();
Set<Object> set = new HashSet<Object>();
set.addAll(listA);
set.addAll(listB);
set.addAll(listC);
EDIT: Did Some Testing
Here's a little test method that shows this in action:
public static void main(final String[] args) {
final String one = new String("one");
final String two = new String("two");
final String three = new String("three");
final String four = new String("four");
final List<String> listA = new ArrayList<String>();
listA.add(one);
listA.add(two);
final List<String> listB = new ArrayList<String>();
listB.add(two);
listB.add(three);
final List<String> listC = new ArrayList<String>();
listC.add(three);
listC.add(four);
final Set<String> set = new HashSet<String>();
set.addAll(listA);
set.addAll(listB);
set.addAll(listC);
System.out.println(set);
}
And the output is:
[two, one, three, four]
This shows the implementation working, but you should obviously keep in mind that the order of the remaining objects might not be want you anticipate or desire.
Yes, you may declare a set of lists, if that's what you're looking for.
Set<List<SomeType>> mySet = new Set<>();
mySet.add(listA);
mySet.add(listB);
mySet.add(listC);
Related
ArrayList<ArrayList<Integer>> treeList = new ArrayList<>();
ArrayList<Integer> aList = new ArrayList<>();
ArrayList<Integer> bList = new ArrayList<>();
aList.add(1);
treeList.add(aList);
bList = treeList.remove(0);
aList.clear(); //bList will be cleared
I know that bList and aList will refer to the same object,so when aList.clear(), bList will clear too, is there any way to make bList a new object.
... is there any way to make bList a new object.
You can copy it; e.g.
bList = new ArrayList<>(treeList.remove(0));
See How to copy Java Collections list
Actually, this looks like a case that would benefit from writing your own custom classes.
As written, your treeList is an open data structure. Anything that has access to treeList or any of its component ArrayList objects can interfere with it. That's OK in some circumstances. But if you want to protect against having different parts of your codebase "mess up" the data structure then you should put the data structure behind an abstraction boundary; e.g.
public class MyThing {
private ArrayList<ArrayList<Integer>> treeList = new ArrayList<>();
public void add(ArrayList<Integer> l){
treeList.add(new ArrayList<>(l));
}
public void remove(int index) {
return new ArrayList<>(treeList.remove(index));
}
}
Notice that MyThing carefully copies the lists when it adds them and when it removes them so that one client of the MyThing API cannot interfere with another one via shared lists.
Obviously, there is a cost in doing this.
Try this. Pass the return of the remove as an argument to the ArrayList constructor.
ArrayList<ArrayList<Integer>> treeList = new ArrayList<>();
ArrayList<Integer> aList = new ArrayList<>();
ArrayList<Integer> bList = new ArrayList<>();
aList.add(1);
treeList.add(aList);
bList = new ArrayList<>(treeList.remove(0));
aList.clear(); //bList will be cleared
System.out.println(bList);
Prints
[1]
Alternatively, instead of assigning:
bList = treeList.remove(0);
you can use List#addAll
bList.addAll(treeList.remove(0));
I have nested ArrayList that looks like that in Java:
myArrayList = [element1, element2, [element3]]
I would like to add elements so the ArrayList will look like that:
myArraylist = [element1, element2, [element3, element4, element5]]
I tried to use;
myArrayList.get(2).add(elemet4);
myArrayList.get(2).add(elemet5);
but as a result I got:
myArraylist = [element1, element2, [element3], element4, element5]
Any hints how to resolve that will be much appreciated.
edit:
My bad, I should have attached Java code and avoid misleading you guys. Anyway here it is:
ArrayList<ArrayList<String>> finalArray = new ArrayList<ArrayList<String>>();
ArrayList<String> finalArrayTempCopy = new ArrayList<String>();
ArrayList<Integer> transactionTemp = new ArrayList<Integer>();
private ArrayList<Integer> addTransaction(){
System.out.println("Enter transaction amount:");
int amount = scanner.nextInt();
scanner.nextLine();
transactionTemp.add(Integer.valueOf(amount));
return transactionTemp;
}
private int searchName(String name){
int indexImienia = customerName.indexOf(name);
return indexImienia;
}
public void sumUp(){
String name = "Tom";
String branch = "First";
int indexImienia = searchName(name);
String transactionsAsString = transactionTemp.toString();
finalArrayTemp.add(name);
finalArrayTemp.add(branch);
finalArrayTemp.add(transactionsAsString);
finalArrayTempCopy = new ArrayList<String>(finalArrayTemp);
finalArray.add(indexImienia, finalArrayTempCopy);
}
Later in the code if I want to add single transaction I use the following method
public void addSingleTransaction(){
int indexImienia = 0;
int amount =20;
finalArray.get(indexImienia).add(2, String.valueOf(amount));
}
Editing my post I realised that the problem might lie with converting ArrayList into string and adding it to finalArray as string. Anyway, I will be grateful for your insight.
i think you looking for
List<Object> list1=new ArrayList<Object>();
List<Object> list=new ArrayList<Object>();
list.add("element1");
list.add("element2");
list1.add("element3");
list.add(list1);
List<Object> listobj=(List<Object>) list.get(2);
listobj.add("element4");
listobj.add("element5");
System.out.println(list);
you are adding element to your parent list not your nested list, for which you have to store the reference of your nested list, then you can add other elements.
Seems like you are looking for:
ArrayList<Object> myArrayList = new ArrayList<Object>();
ArrayList<Integer> list1 = new ArrayList<Integer>;
myArrayList.add(element1);
myArrayList.add(list1);
Or
ArrayList<ArrayList<Integer>> myArrayList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list1 = new ArrayList<Integer>;
ArrayList<Integer> list2 = new ArrayList<Integer>;
list1.add(element1);
list2.add(element2);
list2.add(element3);
myArrayList.add(list1);
myArrayList.add(list2);
Assuming, element is an Integer
As per the psuedo code shared, There is some issue with your main array declaration.
ArrayList can only have one type of data in it. Therefore, your declaration of array can be like :
ArrayList<Element> arr = new ArrayList<Element>();
or to store List in it:
ArrayList<ArrayList<Element>> ar2 = new ArrayList<ArrayList<Element>>();
If you wish to store both type of values in same structure
you can use Object for storing any type of value, since it is the root of all classes.
In this case your declaration will be something like:
ArrayList<Object> arrOuter = new ArrayList<Object>();
Element e1 = new Element();
Element e2 = new Element();
arrOuter.add(e1);
arrOuter.add(e2);
ArrayList<Element> arrNested = new ArrayList<Element>();
Element e3 = new Element();
arrNested.add(e3);
arrOuter.add(arrNested);
But in this case you can not directly call add method on data returned by arrOuter, since the data returned is of Object class. You have to explicitly cast it to list and then add another data.
Element e4 = new Element();
Element e5 = new Element();
((ArrayList) arrOuter.get(2)).add(e4);
((ArrayList) arrOuter.get(2)).add(e5);
I'm trying to initialize a List in Java but I want to know if there's a more elegant way of initializing multiple lists with the same types.
So far I've done the following:
List<Model> list1 = new List<>();
List<Model> list2 = new List<>();
List<Model> list3 = new List<>();
But I'm trying to initialize about 10 different lists of the same type and it seems very ugly.
I've also tried doing:
List<Model> list1, list2, list3 = new List<>();
But this doesn't work.
After searching for the answer, all I could find were tips on how to initialize an array with multiple variables in one line using the asList() method but that's not what I'm trying to do.
Is this even possible?
You can use a Map where the key represents the list name and the value represents a List
Map<String,List<Model>> lists = new HashMap<>();
You can then populate the list in a for loop :
for(int i=0;i<10;++i) {
lists.put("list"+(i+1),new ArrayList<Model>());
}
You can access the lists using :
lists.get("list1").add(new Model(...));
lists.get("list2").add(new Model(...));
Disclaimer : I have not tried compiling this code since I am not on a computer.
If you have 10 lists or whatever, it's time to think: probably you need an array or list of lists.
List<List<Model>> lists = new ArrayList<>();
for(int i=0; i<10; i++) lists.add(new ArrayList<>());
// later in code instead of list5.add(...)
lists.get(5).add(...)
List is an interface (abstract type) and cannot be instantiated. You will have to use ArrayList as shown below. You can try:
List<Model> list1 = new ArrayList<Model>(), list2 = new ArrayList<Model>();
This should work as well
List<Model> list1 = new ArrayList<Model>(), list2 = new ArrayList<Model>(), list3 = new ArrayList<Model>();
The closest possible thing that you can do is following
List<Model> a = new ArrayList<>(), b = new ArrayList<>(), c = new ArrayList<>(), d = new ArrayList<>();
But either of the approach you consider has same memory consumption impact.
Here's my answer:
#SuppressWarnings({"unchecked"})
List<Model>[] lists = new List[3];
for(List list : lists) {
list = new ArrayList<Model>();
}
List<Model> list1 = lists[0];
List<Model> list2 = lists[1];
List<Model> list3 = lists[2];
I need to use generics for my nestList. What syntax I can use so that both Integer and String lists can be added to nested lists as well as of any other types ?
// integer list
List<Integer> listInteger = new ArrayList<Integer>(Arrays.asList(1, 2));
// string list
List<String> listString = new ArrayList<String>(Arrays.asList("abc", "xyz"));
// nested lists.
List nestedList = new ArrayList();
nestedList.add(listInteger);
nestedList.add(listString);
nestedList.add("A");
Since you want to store lists AND non-collection objects ("A") you should store Objects in your collection, like:
import java.util.*;
public class Main {
public static void main(String[] args)
{
// integer list
List<Integer> listInteger = new ArrayList<Integer>(Arrays.asList(1, 2));
// string list
List<String> listString = new ArrayList<String>(Arrays.asList("abc", "xyz"));
// nested lists.
List<Object> nestedList = new ArrayList<Object>();
nestedList.add(listInteger);
nestedList.add(listString);
nestedList.add("A");
}
}
Just note that List<Object> is just to avoid the compiler from complaining that your collection doesn't have a type. Effectively, List<Object> and List are the same thing.
You could have suppressed the warning using this:
import java.util.*;
public class Main {
#SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args)
{
// integer list
List<Integer> listInteger = new ArrayList<Integer>(Arrays.asList(1, 2));
// string list
List<String> listString = new ArrayList<String>(Arrays.asList("abc", "xyz"));
// nested lists.
List nestedList = new ArrayList();
nestedList.add(listInteger);
nestedList.add(listString);
nestedList.add("A");
}
}
But ultimately, the solution in general is not good.
I don't have all your requirements, but a better idea would be to have an object to store all your collections and objects. You code would be cleaner and free from #SuppressWarnings, which are considered bad.
Something like:
MyObj myobj = new MyObj();
nestedList.setIntegers(listInteger);
nestedList.setStrings(listString);
nestedList.setSomeProperty("A");
Make the type as Object as you are adding different types of Objects(list,String) into the nestedList.
List<Object> nestedList = new ArrayList<Object>();
You can also use type as List only if you are adding list Objects in nestedList.
List<List> nestedList = new ArrayList<List>();
But this will error out if you try to add nestedList.add("A") , also It will also prompt a warning for using raw types.
Making it List<Object> = new ArrayList<>(); would allow you to add any type of Object regardless of type.
Just change this line
List<List> nestedList = new ArrayList<List>();
And it is, because you are storing list in lists, the type is List :)
I am new to java .
I have 2 ArrayLists of Strings
List<String> a= [2,14]
List<String> b= [2,3,4,5]
I want two new ArrayLists
1) List has the value which is in b but not in a
List<String> c= [3,4,5]
2) List has the value a but not in b
List<String> d=[14]
I tried:
List<String> c = new ArrayList<String>(b);
c.removeAll(a);
System.out.println("c::::::::::::::::::::::::::::::"+c); // 2,3,4,5
which is not removing the values of List a
Complete Code
public static void updatePartyType(List<String> oldPartyKeys, List<String> newPartyKeys, String customerCode) {
System.out.println("oldPartyKeys--->"+oldPartyKeys);// 2,14
System.out.println("newPartyKeys--->"+newPartyKeys); // 2,3,4,5
System.out.println("oldPartyKeys class --->"+oldPartyKeys.getClass());// class java.util.ArrayList
List<String> newlySelectedPartyKeys = new ArrayList<String>(newPartyKeys);
newlySelectedPartyKeys.removeAll(oldPartyKeys);
System.out.println("newlySelectedPartyKeys::::::::::::::::::::::::::::"+newlySelectedPartyKeys);
You're really proposing set operations more than list operations - in which case you'd be better off using a HashSet than an ArrayList. Then you could use Collection<E>.removeAll:
Set<String> a = ...;
Set<String> b = ...;
Set<String> c = new HashSet<String>(b);
c.removeAll(a);
Set<String> d = new HashSet<String>(a);
d.removeAll(b);
(This will work for ArrayList as well as HashSet - I've only changed to using sets because it's a more appropriate type when you want set-based operations.)
Or better, use Guava's Sets.difference method:
Set<String> a = ...;
Set<String> b = ...;
Set<String> c = Sets.difference(b, a);
Set<String> d = Sets.difference(a, b);
This will create views on the differences - so changes to the original sets will be reflected in the views. You can effectively take a snapshot of a view by creating a new HashSet:
Set<String> snapshot = new HashSet<String>(c);
This can be done by using the removeAll method:
List<String> c = new ArrayList<>(b);
c.removeAll(a);
List<String> d = new ArrayList<>(a);
d.removeAll(b);
take a look at the addAll() and removeAll() in ArrayList
now you need b\a which is b.removeAll(a)
and a\b which is a.removeAll(b)
A working example (this is for those who are new to Java, so it's verbose):
public static void main(String[] args) {
// first we want to create the lists
// create list a
List<String> a = new ArrayList<String>();
// add members to a
a.add("2");
a.add("14");
// create list b
List<String> b = new ArrayList<String>();
// add members to b
b.add("2");
b.add("3");
b.add("4");
b.add("5");
// create a list in which we store the "filtered" list - duplicated from
// a
List<String> aMinusB = new ArrayList<>(a);
// "filter" using "removeAll" and giving the list b as the argument
aMinusB.removeAll(b);
System.out.println("A minus b:");
// this is short for
// "iterate over the entire list, naming the currently iterated node s"
for (String s : aMinusB) {
System.out.println(s);
}
// duplicate list b in the same manner as above
List<String> bMinusA = new ArrayList<>(b);
// "filter" using "removeAll" and giving the list a as the argument in
// the same manner as above
bMinusA.removeAll(a);
System.out.println("B minus a:");
// this is short for
// "iterate over the entire list, naming the currently iterated node s"
// in the same manner as above
for (String s : bMinusA) {
System.out.println(s);
}
}
Convert your lists to Set instances. Then you can easily find the difference of sets by your own implementation or using a 3rd party library like Google Guava which has Sets.difference(), for example.
addAll elements, then removeAll elements that appears in a.
The time complexity is O(n).