java Collection FrameWork - java

i want to store Arraylist inside Another List, some thing like this i know its wrong but pretty much like this....
List list=new ArrayList();
list.add(new("element1","element2","element3",element4=?);
list.add(new("element5","element6","element7",element8=?);
now if u see the above code its ok and fine to add elements or first row to list up to third element but the fourth element is another array[string array] how to add it or append it to the first row of element.
same with the second row.
NOTE:- element4 and element8 are also differ in length means element4 has 2 string and element 8 has 10 strings.
when i display the list it should show list like this
The first row of list is
element1 element2 element3 element4.1 element4.2
the second row of list is
element5 element6 element7 element8.1 element8.2 element8.3 element8.4 element8.5 element8.6 element8.7 element8.9 element8.10

So from what I understood about your question, you need a List<List<String>>. Do it as follows:
List<String> strs1 = new ArrayList<String>();
strs1.add("element1");
strs1.add("element2");
List<String> strs2 = new ArrayList<String>();
strs2.add("element3");
And then
List<List<String>> listOfList = new ArrayList<List<String>>();
listOfList.add(strs1);
listOfList.add(strs2);
OR
List<List<String>> asList = Arrays.asList(strs1, strs2);

Have you tried following way:
List list = new ArrayList();
list.add(Arrays.asList("element1", "element2", "element3",
Arrays.asList("element4.1", "element4.2")));
list.add(Arrays.asList("element5", "element6", "element7",
Arrays.asList("element8.1", "element8.2", "element8.3")));
// print values
System.out.println(list.get(0));
System.out.println(list.get(1));

Unify it to a List of lists of lists, a three dimensional matrix - even if your first elements are single values, it makes sense to wrap them in lists just to simplify the code:
List<List<List<String>>> matrix = new ArrayList<List<List<String>>>();
List<List<String>> row = new ArrayList<List<String>>();
matrix.add(row);
List<String> column1 = new ArrayList<String>();
column1.add("element1");
row.add(column1);
List<String> column2 = new ArrayList<String>();
column1.add("element2.1");
column1.add("element2.2");
row.add(column2);

You can add lists to other lists by doing something like so: List<List<String>> myList = new ArrayList<List<String>>();.... However, seeing that you are adding items which have a different type, I would recommend you do the following (assuming you always have 3 array lists and 1 array):
Create a new class which takes in 4 arguments, these being the 3 array lists and the 1 array.
Have your class override its own toString() method in such a way that it will iterate over the elements and print their content in whatever way you would like.
Create an list using generics, using something like this: List<MyClass> myList = new ArrayList<MyClass>();.... In this case, MyClass is the class I have described in point 1. This will allow you to create a type safe structure which does not need to do any casting, thus making your code look cleaner and probably run slightly faster.
Seeing that you say that the elements can contain list of strings of various lengths, you can do something like this:
public class MyClass
{
private List<String> arrayList1;...
private String[] myArray;...
public MyClass(List<String> list1, ..., String[] myArray)
{
this.arrayList1 = list1;
this.myArray = myArray;
...
}
...
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
//iterate adding your list contents to your string builder.
return sb.toString();
}
}
Adding your elements then will be something like this:
...
List<String> arrayList1 = ...;
arrayList1.add("...");...
String[] myArray = ...;
MyClass myClass = new MyClass(arrayList1, ..., myArray);
System.out.println(myClass.toString());

Related

How to dynamically change a list value to another list in Java or Groovy

For Example, I have a list like below,
list1 = ["a","b","c"] now i want to add value to the list[1] index and that index will be another list like,
list2 = ["w","x","y"]
The output will be ["a",["b","w","x","y"],"c"] I don't want to replace 1 index
Is it possible?
Your base list contains two types: String and List<String>
You can create a list as your base list in java but is not a good idea because you are mixing types. That is a bad practice. You should avoid raw types.
You could use a helper method like :
private static List mergeIntoList(List source, List listToAdd, int index) {
List innerList = new ArrayList(listToAdd);
innerList.add(0, source.get(index));
List mergedList = new ArrayList(source);
mergedList.set(index, innerList);
return mergedList;
}
Exemple:
List source = Arrays.asList("a", "b", "c");
List listToAdd = Arrays.asList("w", "x", "y");
System.out.println(mergeIntoList(source, listToAdd, 1));
output: [a, [b, w, x, y], c]
But I repeat, you should avoid raw types, so this solution is not recommended
It's possible, but not very type safe (=don't do it). You could use a List and then add your values, which could be any type of Object (Integer String... or another List).
When retrieving the Objects you would need to check what type they are with instanceof and then cast them.
In java it is not possible taking type of list1 as String.
Type of list1 seems String and you are adding another list into list1 which is not correct.
But it is possible taking type list1 as Object
List<Object> list1=new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<Object> innerlist=new ArrayList<>(); //Inner List
list1.add(innerlist);
However it is not recommended way.
You can add value to a specific index as below
List list = new ArrayList();
List l1 = new ArrayList();
l1.add("3");
l1.add("4");
list.add("1");
list.add("5");
list.add(1, l1);
Please make sure that index in the list size, otherwise will get the IndexOutOfBoundsException
Please try below logic
public List replaceIndex(List original, List replace, int index) {
Object object = original.remove(index);
replace.add(0, object);
original.add(index, replace);
return original;
}

Converting List<List<String>> to array

I have elements that is declared in a list variable such as:
List<List<String>> textList = new ArrayList<>();
The elements are added such as:
textList.add(Arrays.asList(p)); //adding elements
The only way I could output the elements inside the variable is by using:
for(List<String> s: textList){
System.out.println(s); }
which output elements like this:
[He is a boy.]
[He likes apple.]
[She is a girl.]
Now, I would like to store them in an array so that the elements will look like this when outputted.
[He is a boy., He likes apple., She is a girl.]
I've tried
String[] textArr = new String[textList.size()];
textArr = textList.toArray(textArr);
for(String s : textArr){
System.out.println(s);}
but I got an error about:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
So, how do I convert the elements inside a list into array using the proper way. Thanks!
Your problem is that you are not storing Strings in your list textList.
textList.add(Arrays.asList(p));
As the type says, you have a List of List of String here.
So you can't take the elements of that list and assume they are Strings. Because they aren't! The error message tells you that: toArray() wants strings it can put into that array of strings, but you give it a List of List of String!
But thing is: what you are describing here doesn't make sense in the first place. Printing strings shouldn't care if strings are in an array or a List.
What I mean is: when you manually iterate a List or an array to print its content, then it absolutely doesn't matter if you iterate a List or an array. The code is even the same:
for (String someString : someCollection) {
System.out.println(someString);
}
someCollection can be both: array or List!
In other words: the idea to turn data that is nicely stored within Lists into arrays for printing simply doesn't make any sense. To the contrary: you are probably calling toString() on your List object, and the result of that ... isn't 100% what you want. But I guarantee you: calling toString() on some array will result in something you totally will not want.
Long story short: forget about converting to Arrays; simply iterate your List of List of Strings and use a StringBuilder to collect the content of that collection the way you want to see it (you simply append those [ ] chars to that builder in those places you want them to see).
(if you insist on that conversion to array, the key point there to understand is that only a List of String can be turned into an array of string. So a List of List ... doesnt work that easy).
Using streams and flatMap, you can do this:
List<List<String>> list = ...;
String[] strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList()).toArray(new String[0]);
This is equivalent to using a loop (You can use two nested for loops as suggested in the comments instead by replacing the addAll, but why?):
List<List<String>> list = ...;
List<String> stringList = new ArrayList<>();
for (List<String> l : list)
stringList.addAll(l);
String[] strings = list.toArray(new String[stringList.size()]);
You can use Iterator in order to go over every element of the list, instance of the for each statement (I personally like the iterators more). The code you could use would be something like
//Your list
List<List<String>> textList = new ArrayList<>();
//The iterators
Iterator<List<String>> itList = textList.iterator();
Iterator<String> itString;
//The string to store the phrases
String s[] = new String[textList.size()];
int i =0;
//First loop, this seeks on every list of lists
while(itList.hasNext()){
//Getting the iterator of strings
itString = itList.next().iterator();
s[i] = "";
//2nd loop, it seeks on every List of string
while(itString.hasNext()){
s[i] = s[i].concat(itString.next());
}
s[i] = s[i].concat(".");
i++;
}

Get String from ArrayList inside an ArrayList inside an ArrayList

I need to get three levels down into an array list. Here is my code on how I create the final product "rowList":
ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();
ArrayList<ArrayList<String>> appList =new ArrayList<ArrayList<String>>();
ArrayList<String> arr = new ArrayList<String>();
int Id = -1;
int cc = rsmd.getColumnCount();
while(rs.next()){
if(Id == -1){
arr.add(rs.getString("name"));
Id= Integer.parseInt(rs.getString("Id"));
}
if(Id!= Integer.parseInt(rs.getString("Id"))){
Id= Integer.parseInt(rs.getString("Id"));
rowList.add(appList);
appList = new ArrayList<ArrayList<String>>();
arr.add(rs.getString("name"));
}
for(int i=2; i < rsmd.getColumnCount();i++){
arr.add(rs.getString(rsmd.getColumnName(i)));
}
appList.add(arr);
arr = new ArrayList<>();
}
rowList.add(appList);
So in the end rowlist will look something like this:
[0]
[0]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]
[0]Property 1
[1]Property 2
[2]Property 3
[1]
[0]Property 1
[1]Property 2
[2]Property 3
So my question would be how to get to the properties, the last level in the nested array? I can use rowList.get(0).get(0).toString() to return the string array, but rowList.get(0).get(0).get(0) doesn't work, and instead gives the error: cannot find symbol.
I would also like to be able to remove a property after I've retrieved it and set it to a string. That part can easily be worked around though, so it isn't vital.
This is because you're using a raw type:
ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();
rowList.get(0) returns an ArrayList. Antoher .get(0) will return an Object, because you're using a raw type. And Object does not have a get method.
But Object does have a toString method, so you can call toString.
You simply have to change the declaration. This can be made easier using the diamond:
ArrayList<ArrayList<ArrayList<String>>> rowList = new ArrayList<>();
ArrayList<ArrayList<String>> appList = new ArrayList<>();
ArrayList<String> arr = new ArrayList<>();
Okay, let's think about the type of each result in the chained calls rowList.get(0).get(0).get(0). The easiest way to do this is to break each call into its own line so that we can figure out the type we need for the variable declaration. First of all, look at the declaration of rowList:
ArrayList<ArrayList> rowList = new ArrayList<ArrayList>();
This tells us that rowList.get(0) will return an ArrayList:
ArrayList arr = rowList.get(0);
Now rowList.get(0).get(0) is equivalent to arr.get(0). But this returns an Object:
Object obj = arr.get(0);
So rowList.get(0).get(0).get(0) is equivalent to obj.get(0). However, Object does not have a method named get(). This is why you get an error message.
In general, you should be very careful when chaining method calls. Typically this syntax is only used when a method returns a reference to the calling object. That way the return type is always the same and much easier to keep track of. When the return type differs on each successive method call, it can be difficult to keep track of.
The problem is that the ArrayList returned by rowList.get(0) is a raw type. So another get() call only returns an Object. You should use generics to specify the type of object in the "rows":
ArrayList<ArrayList<ArrayList<String>>> rowList = new ArrayList<>();
As you see here, generics can be used as the type inside of any <> just like you already did for the outermost level of ArrayList in your originaly code. (Note that in JDK 7+, you can use the diamond operator when creating an ArrayList. This greatly reduces duplicating the type information that already appears in the declaration.)
Better yet, you can declare your variables using the List interface in order to provide some flexibility in the concrete type used:
List<List<List<String>>> rowList = new ArrayList<>();

ArrayList of Array of Strings

What is the difference between the two data structures defined below?
The second one is an ArrayList, whose elements have type 'String'. But what is the first data structure?
The initializations would also be different. Can anyone give an example here?
ArrayList<String>[] temp1;
ArrayList<String> temp2;
ArrayList<String>[] temp1;: This is an Array of ArrayList's that are containing Strings
ArrayList<String> temp2;: This is an ArrayList containing Strings
If you want an ArrayList of Arrays of Strings, you would have to do a ArrayList<String[]> temp3;. Note the position of the different brackets.
To initialize:
// create an array with 10 uninitialized ArrayList<String>
ArrayList<String>[] temp1 = new ArrayList[10];
// create empty lists that can be filled
for (int i=0; i<temp1.length; i++)
temp1[i] = new ArrayList<String>();
// create an empty list of Strings
ArrayList<String> temp2 = new ArrayList<String>();
// create an empty list of String arrays
ArrayList<String[]> temp3 = new ArrayList<String[]>();
I provide some example to differentiate the Array of ArrayList and ArrayList of String
public class ArrayOfArrayList {
public static void main(String[] args) {
// Declare the Array of ArrayList
List<String>[] arrayOfList = new ArrayList[2];
// Declare the Object of ArrayList
for(int i = 0; i < arrayOfList.length; i++) {
arrayOfList[i] = new ArrayList<>();
arrayOfList[i].add("" + (i + 1));
arrayOfList[i].add("" + (i + 2));
}
// Print out the result
for(List<String> list : arrayOfList) {
for(String str : list) {
System.out.println(str);
}
}
// Declare the Object of ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("1");
arrayList.add("2");
// Print out the result
for(String str : arrayList) {
System.out.println(str);
}
}
}
The first data structure is an array of ArrayLists containing string objects
The first is an array of classes of the type ArrayList<String>. The second is simply an ArrayList<String> (ArrayList of Strings.)
In terms of initialisations:
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10];
ArrayList<String> temp2 = new ArrayList<String>();
The first initialisation has to specify a size for the array (note this is not a size for the ArrayList) and this is where the 10 comes from in my example. It can be any size you choose of course, 10 is just an arbitrary example. It will also generate a warning, but, if you really want an array of ArrayList<String> this is AFAIK the only way for now (the reason stems from the fact generics in Java aren't reified, but array types are.)
The second one is an ArrayList, whose elements have type 'String'. But what is the first data structure?
On the surface, it would appear to be an array of lists (containing strings). However arrays and generics don't play very well together. From the article:
Another consequence of the fact that arrays are covariant but generics are not is that you cannot instantiate an array of a generic type (new List<String>[3] is illegal), unless the type argument is an unbounded wildcard (new List<?>[3] is legal). Let's see what would happen if you were allowed to declare arrays of generic types:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
The last line will throw a ClassCastException, because you've managed to cram a List<Integer> into what should have been a List<String>. Because array covariance would have allowed you to subvert the type safety of generics, instantiating arrays of generic types (except for types whose type arguments are unbounded wildcards, like List<?>) has been disallowed.
Yes, first is the Array of ArrayList and will have strings value in it.
second statement is only array list of Strings value.

adding two arraylists into one

I want to check branchList whether has same element or not, if same put branchList and tglList element separate arraylist and put that arraylist into another arraylist,
The result I want is BranchList1 have 2 arraylist where 1st arraylist contain for element '1' and 2nd arraylist contain element '2' and TglList1 have 2 arraylist as element, but what i get is both 1st and 2nd array get same value.
How can this be done?
ArrayList branchList = new ArrayList();
branchList.add("1");
branchList.add("1");
branchList.add("1");
branchList.add("2");
branchList.add("2");
branchList.add("2");
ArrayList tglList = new ArrayList();
tglList.add("5");
tglList.add("10");
tglList.add("20");
tglList.add("100");
tglList.add("500");
tglList.add("1000");
ArrayList newBranchList = new ArrayList();
ArrayList newTglList = new ArrayList();
ArrayList BranchList1 = new ArrayList();
ArrayList TglList1 = new ArrayList();
ArrayList abc = new ArrayList();
String checkBranch = new String();
for(int i=0;i<branchList.size();i++){
String branch = branchList.get(i).toString();
if(i==0 || checkBranch.equals(branch)){
newBranchList.add(branch);
newTglList.add(tglList.get(i).toString());
}else{
BranchList1.add(newBranchList);
TglList1.add(newTglList);
newBranchList.clear();
newTglList.clear();
newBranchList.add(branch);
newTglList.add(tglList.get(i).toString());
}
if(i==(branchList.size()-1)){
BranchList1.add(newBranchList);
TglList1.add(newTglList);
}
checkBranch = branch;
}
}
so expected result is as below:
BranchList1 = [ [1,1,1],[2,2,2]]
TglList1 = [[5,10,20],[50,100,200]]
but what I get is
BranchList1 = [ [2,2,2],[2,2,2]]
TglList1 = [[50,100,200],[50,100,200]]
How can I modify the code
I didn't thoroughly read through your code (and I don't quite get what you're asking for), but if you want to merge (add the elements of) branchList and tglList to TglList1, try this:
TglList1.addAll(branchList);
TglList1.addAll(tglList);
After that, TglList1 should contain all elements of both lists. If you need the list to be sorted, you might want to call Collections.sort(TglList1) afterwards (just note that sorting strings might place "100" before "2", due to "1" being lexically smaller than "2").

Categories

Resources