adding two arraylists into one - java

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").

Related

Java 2D arraylists

I cant understand 2D arraylists, they are confusing me, I can understand 2D arrays however as I worked with them before in C and in Python as "nested lists"
can someone explain the difference between these 2 codes?
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>(); // added ()
temp.add("Hello world.");
temp.add("sup");
biDemArrList.add(temp);
ArrayList<String> it = new ArrayList<String>();
it.add("1");
it.add("0");
biDemArrList.add(it);
System.out.println(temp);
System.out.println(it);
System.out.println(biDemArrList);
and this one :
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
for (int i = 0; i < 12; i++) {
table[0][5].add("0");
}
for (int i = 0; i < 9; i++) {
table[1][1].add("1");
}
System.out.println(table[0][5]);
System.out.println(table[9][9]);
Like in C arrays of non primitive types are not initialized (only arrays of primitive types are...).
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
Here you create an array of 100 elements but you only initialize 2 Elements.
ArrayList is resizable-array implementation of the List interface. This class. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays.
You can add any object to List, e.g. null, String, Object, String[]. ArrayList<String> also is object, it's means you can add to list.
You said I have ArrayList which can add other ArrayList. The result will be ArrayList<ArrayList>>.
But we want to add only String's to inner ArrayList. And we create ArrayList<String>
So, We have list of string ArrayList<String> which can be added to other list ArrayList<ArrayList>>
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();
ArrayList<String> subArrayList = new ArrayList<String>();
/* Added elements into subArrayList */
subArrayList.add("Yogesh");
subArrayList.add("Pawar");
ArrayList<String> subArrayList2 = new ArrayList<String>();
/* Added elements into subArrayList2 */
subArrayList2.add("Java");
subArrayList2.add("Programmer");
/* Adding elements into mainArrayList */
mainArrayList.add(subArrayList);
mainArrayList.add(subArrayList2);
for (int i = 0; i < mainArrayList.size(); i++) {
for (int k = 0; k < mainArrayList.get(i).size(); k++) {
System.out.print(" " + mainArrayList.get(i).get(k));
}
System.out.println();
}
The difference between
List of List
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
and
Array of Array of List
ArrayList[][] table = new ArrayList[10][10];
Is that the second one is not actually two-dimensional, it is three-dimensional. You end up with 10 Arrays of length 10 that you can put ArrayLists into. Where as in the List of List example you have a List you can put other Lists into.
Using the Object[][] or primitive[][] you have to allocate the 2D array with exact number of "rows" and "columns" like new Object[2][8].
On the other hand with ArrayList<ArrayList<...>> try to understand the following code:
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<>();
ArrayList<String> a0 = new ArrayList<>();
a0.add("string_1");
ArrayList<String> a1 = new ArrayList<>();
a1.add("strfdfas");
a1.add("adfadsfasdfasdfasfaf");
biDemArrList.add(a0);
biDemArrList.add(a1);
biDemArrList.stream().forEach(System.out::println);
The first "row" has one element, and the second one has two elements. This is only an example... With arr[][] you cannot achieve this.
What is reason behind this not sure, But i would share my experience here,
Array is the fixed size of data structure, once we initialize the array we can't modify the size. To resolve this we have ArrayList comes to picture. Arraylist has variable lenght.
In your second code snippet, if you are looking for fixed sized of 2D ArrayList, I would suggest to go 2D Arrays.
If you want to get benefit of Collection features, later you can convert Arrays to ArrayList object.

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++;
}

Manually accessing an ArrayLists with a ArrayList

I'm working with Depth First Search program and I'm trying to create a Adjacency List Representation.
I read through some articles stating that an creating ArrayLists within an ArrayList would be the best representation.
Let's say I initialized the arraylist within a arraylist like so:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
My question is how would you input data into the arraylist MANUALLY. I'm trying to understand the concept of arraylist with an arraylist before I begin my programming. If someone could possibly insert data into this arraylist so I could see the proper way of setting up.
Any additional input on anything I might need or take in consideration is recommended.
BTW: This is not a homework assignment just using personal time looking through my old textbooks.
Let's say you want to add 2 lists, one with 1 and 2 and the other with 10 and 20. A very manual way of adding could be:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
adjList.add(new ArrayList<Integer>()); // initialise new ArrayList<Integer>
adjList.get(0).add(1); // add value one by one
adjList.get(0).add(2);
adjList.add(new ArrayList<Integer>());
adjList.get(1).add(10);
adjList.get(1).add(20);
You could also write it this way:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
ArrayList<Integer> a1 = new ArrayList<Integer>(); // initialise new ArrayList<Integer>
a1.add(1); // add value one by one
a1.add(2);
adjList.add(a1);
ArrayList<Integer> a2 = new ArrayList<Integer>(); // initialise new ArrayList<Integer>
a2.add(10); // add value one by one
a2.add(20);
adjList.add(a2);
Well, a list of a list of Integer objects could be done as such:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
List<Integer> li = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
li.add(i);
}
adjList.add(li);
Add to each sublist, and then add the sublist.
The adjList can contain the elements of the type List<Integer>, so create one and add using add(E element) function as we would for adding an element:
ArrayList<Integer>aList = new ArrayList<>();
adjList.add(aList);
Then to add an element to the element(which has the type List<Integer>) of adjList: you can try getting it using get(index) and add your element:
adjList.get(0).add(10);
adjList.get(0).add(22);
Try adding a second list and get it's index using get(1) and add the Integer element to the list at index 1 as the above example suggest. There are other known function too. Please check the class ArrayList<E> documentation page.
This will help
public static void main(String[] args){
//creating a new ArrayList of List of Integers
ArrayList<List<Integer>> integerListContainer = new ArrayList<List<Integer>>();
//Creating the first child arraylist of Integers
ArrayList<Integer> firstChildintegerList = new ArrayList<Integer>();
//filling the values 1,2,3 in it
firstChildintegerList.add(1);
firstChildintegerList.add(2);
firstChildintegerList.add(3);
//adding this integer list to the parent list
integerListContainer.add(firstChildintegerList);
//Creating the second child arraylist of Integers
ArrayList<Integer> secondChildintegerList = new ArrayList<Integer>();
//filling the values 10,20,30 in it
secondChildintegerList.add(10);
secondChildintegerList.add(20);
secondChildintegerList.add(30);
//adding this integer list to the parent list
integerListContainer.add(secondChildintegerList);
System.out.println("Printing the parent list to see what it has: ");
System.out.println(integerListContainer.toString());
}
Hope it clearly explains what happens

How to copy java.util.list Collection

I am implementing a Java class responsible for ordering java.util.List. The problem comes when I use this class. I'm able to ordering the list but I want to copy the "original" list without modification so that I could register every change made on the original list. The sorted list contains object and one of its fields stores a classification id, and this id it is updated with the index value of the list.
I tried to use clone method and it keeps the list unsorted but the changes made on original list are updated in the clone list too.
Is there any way to accomplish it?
My Code:
List<Torero> listaTorero = tbTlgTorerolHome.findByExample(new Torero());
List<Torero> listaToreroTemp = ((List<Torero>) ((ArrayList<Torero>) listaTorero).clone());
Clasificacion clasificacion = new Clasificacion();
Iterator<Torero> iterTorero = clasificacion.getClasificacion(listaTorero, torero).iterator(); //Sorting List
A Clasificacion method:
public List<Torero> getClasificacion(List<Torero> listaToreroTemp, Torero torero)
{
List<Torero> listaTorero = new ArrayList<Torero>();
Collections.sort(listaToreroTemp,new ToreroClasifiacionComparator());
Iterator<Torero> iterTorero = listaToreroTemp.iterator();
int index=1;
while(iterTorero.hasNext())
{
Torero toreroTemp = iterTorero.next();
toreroTemp.setNumClasificacion(index);
listaTorero.add(toreroTemp);
index=index+1;
}
return listaTorero;
}
You may create a new list with an input of a previous list like so:
List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);
This will allow you to modify the order or what elemtents are contained independent of the first list.
Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.
example:
MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"
Edit
To avoid this you need a deep copy of each element in the list like so:
List<Torero> one = new ArrayList<Torero>();
//add elements
List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
Torero copy = deepCopy(t);
two.add(copy);
}
with copy like the following:
public Torero deepCopy(Torero input){
Torero copy = new Torero();
copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
return copy;
}
Use the ArrayList copy constructor, then sort that.
List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);
After making the copy, any changes to newList do not affect oldList.
Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

java Collection FrameWork

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

Categories

Resources