How to convert a nested list into a single list in java?
List list = new ArrayList();
List newList = new ArrayList();
List<Integer> list1 = new ArrayList<Integer>();
list1.add(2);
list1.add(4);
list.add(5);
list.addAll(list1);
list.add(6);
How can i add the elements of list to newList so that when i print newList
it prints
[5,2,4,6]
Unless there is something you're not telling us, it is simply a repeat of what you have already done:
newList.addAll(list);
As has been said in the comments though, you really should be using full generic typing for your list variables:
List<Integer> list = new ArrayList<>();
List<Integer> newList = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
You shouldn't be using raw types, and you can call newList.addAll(list); -
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(); // <-- diamond operator, Java 7 and up.
List<Integer> newList = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
list1.add(2);
list1.add(4);
list.add(5);
list.addAll(list1);
list.add(6);
newList.addAll(list); // <-- here
System.out.println(newList);
}
Output is the requested
[5, 2, 4, 6]
You already used a possible way with
list.addAll(list1)
Another way would be walking through the list resp. using it's iterator
to fetch and put all items into the newList.
Have a look at the API for more detailed info: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)
for(int i=0;i<list.size();i++){
if(list.get(i) instanceof Integer){
newlist.add(list.get(i));
}else{
newlist.addAll((ArrayList)list.get(i));
}
}
The list that has to hold another list should be defined properly, rest working will be same. Refer below:
import java.util.List;
import java.util.ArrayList;
public class demo2 {
public static void main(String[] args) {
List<List<Integer>> nestedList = new ArrayList<>();
List<Integer> list = new ArrayList<>();
list.add(1);
nestedList.add(list);
System.out.println(nestedList);
}
}
Related
i need to convert this list: List<double[]> test = new ArrayList<>();
to an 2 dimensional Array with an structure like this :
double[][] test2 = {{3.17, 26.348}, {3.65, 24.198}, {3.28, 25.085}, {3.37, 22.461},
{2.57, 23.740}, {3.60, 24.786}, {3.50, 23.374}, {2.98, 23.725},
{2.54, 23.227}, {3.41, 26.920}..........};
i already tried things like this but it did not work :
List<String[]> list=new ArrayList<String[]>();
double[][] matrix=new double[x34.size()][];
matrix=list.toArray(matrix);
If you are using Java 11 or higher, each collection class has a toArray method which you can use. Example:
List<double[]> myList = List.of(new double[]{3.17, 26.348},
new double[]{3.65, 24.198},
new double[]{3.28, 25.085},
new double[]{3.37, 22.461});
double[][] result = myList.toArray(double[][]::new);
I have stored these comma separated String in an ArrayList.
[<b>SELL 512<\/b> lots of <b>xyz18#112.00<\/b>, <b>BUY 513<\/b> lots of <b>abc#113.00<\/b>]
I want to remove all the HTML Tags and then further I want to store them in different array List.
Say for eg I want my output something like this.
List3: [SELL, BUY]
List4: [512, 513]
List5: [xyz, abc]
List6: [112, 113]
List<String> List1 = new ArrayList<>();
List<String> List2 = new ArrayList<>();
List<List<String>> Tuples = new ArrayList<List<String>>();
List<String> List3 = new ArrayList<>();
List<String> List4 = new ArrayList<>();
List<String> List5 = new ArrayList<>();
List<String> List6 = new ArrayList<>();
for (int i = 0; i < List1.size(); i++) {
String var = List1.get(i).trim();
for (String x : var.split("\\<.*?\\>|\\#|\\,*$|\\.", 7)) {
List2.add(x);
}
Tuples.add(List2);
}
System.out.println(Tuples);
for (int i = 0; i < Tuples.size(); i++) {
List3.add(Tuples.get(i).get(1).split("\\s")[0].replaceAll("SELL","0").replaceAll("BUY","0"));
List4.add(Tuples.get(i).get(1).split("\\s")[1]);
List5.add(Tuples.get(i).get(3));
List6.add(Tuples.get(i).get(4));
}
System.out.println(List3);
System.out.println(List4);
System.out.println(List5);
System.out.println(List6);
}
But this fetches me output something like this:
List3: [SELL, SELL]
List4: [512, 512]
List5: [xyz, xyz]
List6: [112, 112]
If you inspect the output of System.out.println(Tuples); you'll notice a problem:
Tuples.add(List2) does not make a copy of List2. You're storing multiple references to the same List2 in Tuples, and appending more data to the same List2. So you end up with a very long list (i.e., List2) containing all tuples concatenated, and that list replicated many times inside Tuples.
Instead of
Tuples.add(List2);
try this instead:
Tuples.add(new ArrayList<>(List2));
List2.clear();
This will make elements of Tuples reference different lists.
I think you are doing it in a way too complicated way, just do:
List<String> inputList = new ArrayList<String>();
inputList.add("<b>SELL 512</b> lots of <b>xyz18#112.00</b>");
inputList.add("<b>BUY 513</b> lots of <b>abc#113.00</b>");
System.out.println("inputList: "+inputList);
List<List<String>> Tuples = new ArrayList<List<String>>();
List<String> list3 = new ArrayList<String>();
List<String> list4 = new ArrayList<String>();
List<String> list5 = new ArrayList<String>();
List<String> list6 = new ArrayList<String>();
for (int i = 0; i < inputList.size(); i++) {
String var = inputList.get(i).trim();
String[] splitArr=var.split("</b>|<b>|\\d*#"); //remove the \\d* if you expect to have xyz18 in output instead of x
list3.add((splitArr[1].split("\\s"))[0]);
list4.add((splitArr[1].split("\\s"))[1]);
list5.add(splitArr[3]);
list6.add(splitArr[4]);
Tuples.add(Arrays.asList(var.replaceAll("</b>|<b>", "")));
}
System.out.println("Tuples: "+Tuples);
System.out.println("list3: "+list3);
System.out.println("list4: "+list4);
System.out.println("list5: "+list5);
System.out.println("list6: "+list6);
OUTPUT:
inputList: [<b>SELL 512</b> lots of <b>xyz18#112.00</b>, <b>BUY 513</b> lots of <b>abc#113.00</b>]
Tuples: [[SELL 512 lots of xyz18#112.00], [BUY 513 lots of abc#113.00]]
list3: [SELL, BUY]
list4: [512, 513]
list5: [xyz, abc]
list6: [112.00, 113.00]
I have n lists, each of which having variable number of elements. I want to find all possible combination of elements across lists.
for eg,
list1 = l11, l12
list2 = l21
list3 = l31,l32
The resulting list should contain
[l11]
[l12]
[l21]
[l31]
[l32]
[l11, l21]
[l12, l21]
[l21, l31]
[l21, l32]
[l11, l31]
[l11, l32]
[l12, l31]
[l12, l32]
[l11, l21, l31]
[l11, l21, l32]
[l12, l21, l31]
[l12, l21, l31]
Please provide some insight into solving the problem. I am implementing the solution in java
The idea behind this recursion is to make all sublists of n-1 lists and then add to every list each element from the first list while maintaining the fact that the element can also be missing from the set (maintaining the full n-1 solution and adding the new possible sets)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Combinations {
public static void main(String[] args) {
List<String> l1 = Arrays.asList("l11", "l12");
List<String> l2 = Arrays.asList("l21");
List<String> l3 = Arrays.asList("l31", "l32");
List<List<String>> lists = Arrays.asList(l1, l2, l3);
List<List<String>> allSubsets = allSubsets(lists);
for (List<String> subset : allSubsets) {
System.out.println(subset);
}
}
static List<List<String>> allSubsets(List<List<String>> lists) {
if (lists.isEmpty()) {
List<String> empty = new ArrayList<>();
return Arrays.asList(empty);
}
List<List<String>> reduced = new ArrayList<>();
reduced.addAll(lists);
List<String> list = reduced.remove(0);
List<List<String>> subsets = allSubsets(reduced);
List<List<String>> newSubsets = new ArrayList<>(subsets);
for (List<String> subset : subsets) {
for (String s : list) {
List<String> newSubset = new ArrayList<>(subset);
newSubset.add(s);
newSubsets.add(newSubset);
}
}
return newSubsets;
}
}
Hi and thanks for reading! I'm currently studying Generics in Java and this is what I'm trying to accomplish:
I need to delete duplicate elements from an ArrayList. Currently, the ArrayList contains integers. I want to first print the original list, and then print the resulting list after removing the duplicates. This is what I have so far. Any help is appreciated!
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(1);
list1.add(1);
list1.add(2);
list1.add(2);
list1.add(2);
list1.add(3);
list1.add(3);
list1.add(3);
removeDuplicates(list1);
System.out.println("Original List with Duplicates: \n" + list1);
System.out.println();
//System.out.println("After removing duplicates: \n" + list2);
}
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){
for(int i = 0; i < list2.size(); i++){
//logic to remove duplicates
}
return list2;
}
You could add the elements to the Set collection. If you want to preserve order you should use LinkedHashSet
Step One
Convert your list to a set.
Set<Integer> aSet = new HashSet<Integer>(list);
Step Two
Convert your set back to a list.
list = new ArrayList<Integer>(new HashSet<Integer>(list));
Why it Works
Sets can only contain unique elements.
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
list1.add(1);
list1.add(1);
list1.add(1);
list1.add(2);
list1.add(2);
list1.add(2);
list1.add(3);
list1.add(3);
list1.add(3);
System.out.println("Original List with Duplicates: \n" + list1);
System.out.println();
list2 = removeDuplicates(list1);
System.out.println("After removing duplicates: \n" + list2);
}
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){
ArrayList<E> usedList = new ArrayList<E>();
ArrayList<E> newList = new ArrayList<E>();
for(int i = 0; i < list2.size(); i++){
E object = list2.get(i);
if(! usedList.contains(object))
{
usedList.add(object);
newList.add(object);
}
}
return newList;
}
Output (as expected):
Original List with Duplicates:
[1, 1, 1, 2, 2, 2, 3, 3, 3]
After removing duplicates:
[1, 2, 3]
If you're working with other types (not java standard like int), then you have to override the equals method, because it's used in the ArrayList contains method.
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){
LinkedHashSet<E> dataSet = new LinkedHashSet<E>(list2.size());
dataSet.addAll(list2);
ArrayList<E> uniqueLists = new ArrayList<E>(dataSet.size());
uniqueLists.addAll(dataSet);
return uniqueLists;
}
Convert the ArrayList to Set, maybe HashSet and then back to an ArrayList that you could sort if you want the numbers in order (the ordering in Sets are not usually not guaranteed).
HashSet hs<Integer> = new HashSet(list1);
ArrayList<Integer> uniqueList = Collections.sort(new ArrayList<Integer>(hs));
There's also various SortedSet, among them TreeSet.
Also, you can use a less error-prone for loop construction:
for (int i : uniqueList) {
System.out.println(i);
}
All the other answers so far create a new list. If you want to modify the list in place, you can iterate through the list while using an auxiliary Set to keep track of all elements already seen. The following works for any List (not just ArrayList) that allows elements to be removed:
public static <E> List<E> removeDuplicates(List<E> list){
ListIterator<E> iter = list.listIterator();
Set<E> seen = new HashSet<>();
while (iter.hasNext()) {
if (!seen.add(iter.next())) {
// element not added--must have already been seen, so remove element
iter.remove();
}
}
return list;
}
An alternative is to dump the entire list into a Set, clear the list, and then add all the element of the set back into the list. Depending on the Set implementation, this may or may not preserve order.
public static <E> List<E> removeDuplicates(List<E> list){
Set<E> unique = new LinkedHashSet<>(list);
list.clear();
list.addAll(unique);
return list;
}
EDIT: If (as per your comment) you wish to completely remove elements that are not unique to start with, you can modify the first approach:
public static <E> List<E> removeNonUnique(List<E> list){
Set<E> seen = new HashSet<>(); // all values seen
Set<E> dups = new HashSet<>(); // all values seen more than once
for (E elt : list) {
if (!seen.add(elt)) {
// element not added--must have already been seen, so add to dups
dups.add(elt);
}
}
// clean out the list
list.removeAll(dups);
return list;
}
Note that since we're not modifying the list during the loop, we don't need to have an explicit iterator.
In Java I am having trouble converting from a Set<Set<String>> to a List<List<String>> and then populating this list with the contents of the Set<Set<String>>
Here is my code:
Set<Set<String>> treeComps = compExtractor.transform(forest); // fine
List<List<String>> components = new List<List<String>>(); // does not work
components.addAll(treeComps); // does not work
You can't instantiate an instance of the List interface, you need to use one of the implementations like ArrayList. Then you can iterate over the outer set in treeComps, create a new ArrayList for each inner set, call addAll on this ArrayList and then add the list to components.
List<List<String>> components = new ArrayList<List<String>>();
for( Set<String> s : treeComps )
{
List<String> inner = new ArrayList<String>();
inner.addAll( s );
components.add( inner );
}
I think only way is iterate over outer set. Get inner set and user new ArrayList<String>(innerSet)
Add above result list to outerlist.
Something like this...
Set<Set<String>> treeComps = compExtractor.transform(forest);
List<List<String>> lists = new ArrayList<List<String>>();
for (Set<String> singleSet : treeComps) {
List<String> singleList = new ArrayList<String>();
singleList.addAll(singleSet);
lists.add(singleList);
}
List<List<String>> components = new Vector<List<String>>();
List<String> n;
for( Set<String> s : trerComps ) {
n = new Vector<String>();
n.addAll( s );
components.add( n);
}