How to iterate arraylist of arrayLists - java

I Have a list which is in
[
[SAM, 12/01/2015, 9A-6P],
[JAM, 12/02/2015, 9A-6P]
]
I need to iterate it.I tried the below code
for (int i = 0; i < list4.size(); i++) {
System.out.println("List" + list4.get(i).toString());
}
//this is giving me [SAM, 12/01/2015, 9A-6P]
but I want to iterate the above one also [SAM, 12/01/2015, 9A-6P].
Can anybody have idea?

You can and should use the fact that every List is also an Iterable. So you can use this:
// Idk what you list actually contains
// So I just use Object
List<List<Object>> listOfLists;
for(List<Object> aList : listOfLists) {
for(Object object : aList) {
// Do whatever you want with the object, e.g.
System.out.println(object);
}
}

Tried your case with below example. Hope it helps
import java.util.ArrayList;
import java.util.List;
public class IterateList {
public static void main(String[] args) {
List<List<String>> myList = new ArrayList<List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("SAM");
list1.add("12/01/2015");
list1.add("9A-6P");
List<String> list2 = new ArrayList<String>();
list2.add("JAM");
list2.add("12/01/2015");
list2.add("9A-6P");
myList.add(list1);
myList.add(list2);
for (List list : myList) {
for(int i=0; i<list.size();i++){
System.out.println(list.get(i));
}
}
}
}
Output:
SAM
12/01/2015
9A-6P
JAM
12/01/2015
9A-6P

Related

How to iterate arraylists within an arraylist, and insert their data onto an array

Let's say I have an array that takes instances of the type "Pessoal":
Pessoal[] teste = new Pessoal[6];
Now let's say I have 2 arraylists that are inside of an arraylist:
static ArrayList<Pessoal> lista_de_profs; // This one has 4
static ArrayList<Pessoal> lista_de_infos; // And this one has 2, matching the 6 on "teste"
// these arrayslists have instances of the type "Pessoal"
ArrayList<ArrayList<Pessoal>> lista_de_docentes = new ArrayList<>();
lista_de_docentes.add(lista_de_profs);
lista_de_docentes.add(lista_de_infos);
How do I iterate through the arraylist (lista_de_docentes) that contains more arraylists (lista_de_profs & lista_de_infos), and get their instances, so I can put them inside the array?
This works if teste's length is 4
for (int i = 0; i < teste.length; i++){
teste[i] = lista_de_profs.get(i);
}
But this only covers one arraylist, and I want all of the ones inside "lista_de_docentes", which are: "lista_de_profs" and "lista_de_infos"
*Some code in here, the language is in Portuguese, but I can change it to english, if it becomes confusing.
I hope I was clear, and thanks.
You can collect all your "Pessoal" elements into a single arraylist and then move the elements to your array
List<Pessoal> all= lista_de_docentes.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
for (int i =0; i < all.size(); i++)
teste[i] = all.get(i);
Or you can directly create the array (in case you don't care about the size)
Pessoal[] teste = lista_de_docentes.stream()
.flatMap(List::stream)
.collect(Collectors.toList())
.toArray(Pessoal[]::new);
You can do this with the stream API.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Pessoal {
public static void main(String[] args) {
ArrayList<Pessoal> lista_de_profs = new ArrayList<>();
ArrayList<Pessoal> lista_de_infos = new ArrayList<>();
ArrayList<ArrayList<Pessoal>> lista_de_docentes = new ArrayList<>();
lista_de_docentes.add(lista_de_profs);
lista_de_docentes.add(lista_de_infos);
Pessoal[] teste = lista_de_docentes.stream()
.flatMap(l -> l.stream())
.collect(Collectors.toList())
.toArray(new Pessoal[0]);
System.out.println(Arrays.toString(teste));
}
}
lista_de_docentes.stream() creates a stream where every element has type ArrayList<Pessoal>.
flatMap returns a stream where every element has type Pessoal.
All the stream [Pessoal] elements are collected and put into a List.
Method toArray (of interface List) converts the List to an array.
Alternatively, if you don't want to use streams:
import java.util.ArrayList;
import java.util.Arrays;
public class Pessoal {
public static void main(String[] args) {
ArrayList<Pessoal> lista_de_profs = new ArrayList<>();
ArrayList<Pessoal> lista_de_infos = new ArrayList<>();
ArrayList<ArrayList<Pessoal>> lista_de_docentes = new ArrayList<>();
lista_de_docentes.add(lista_de_profs);
lista_de_docentes.add(lista_de_infos);
ArrayList<Pessoal> temp = new ArrayList<>();
for (ArrayList<Pessoal> list : lista_de_docentes) {
for (Pessoal p : list) {
temp.add(p);
}
}
Pessoal[] teste = new Pessoal[temp.size()];
temp.toArray(teste);
System.out.println(Arrays.toString(teste));
}
}
By the way, you should consider adopting Java naming conventions.

Removing Duplicates in an ArrayList by creating a Method

I have to write a method called removeDups that accepts an ArrayList of Strings and returns a copy of the ArrayList with all the duplicates removed. I have to return a new ArrayList with no duplicate basically.
import java.util.ArrayList;
public class Duplicates {
public static ArrayList <String> removeDups(ArrayList<String> myArray) {
for (String item: myArray ) {
ArrayList <String> noDuplicate = new ArrayList <String>();
if (!noDuplicate.contains(item)) {
noDuplicate.add(item);
}else
;
return noDuplicate;
}
}
}
As a beginner coder, I am having trouble writing this code.
You need to modify few things to make it work (and to have cleaner code):
when you do not need ArrayList<String> you should work with interface List<String>
you should initiate noDuplicate array in the first line of method
you should check the condition !noDuplicate.contains(item) and if so just add item to noDuplicate list
rename the method from removeDups to removeDuplicates
Working code:
public static List<String> removeDuplicates(List<String> myArray) {
List<String> noDuplicate = new ArrayList<>();
for (String item : myArray) {
if (!noDuplicate.contains(item)) {
noDuplicate.add(item);
}
}
return noDuplicate;
}
If you will take a look on Java streams you can do the same thing using:
List<String> noDuplicate = myArray.stream()
.distinct()
.collect(Collectors.toList());

How do I create an array list of array lists in java? [duplicate]

This question already has answers here:
2d ArrayList in Java adding data
(2 answers)
Closed 7 years ago.
I currently have an array of arrays and that would work fantastic, except I just realized that I don't know the length of all of the arrays that I need. So I have to switch to ArrayList. I'm used to having an array of arrays and I know how to iterate through them. How do you do the same thing with ArrayLists?
The following works... until I need to change line size through my iterations.
Person[][] nameList = new Person[yearsBack][lines];
for (int i=0; i<yearsBack; i++) {
for (int j=0; j<lines; j++) {
nameList[i][j] = new Person(name, gender, rank);
This should do it:
List<List<Object>> listOfLists = new ArrayList<>();
To loop through:
for(List<Object> list : listOfLists){
for(Object obj : list){
//do stuff
}
}
ArrayList < Objects > can hold the Arraylist Objects and thus you can have the array of arraylists.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Object> mainAl = new ArrayList<Object>();
ArrayList<Integer> al1 = new ArrayList<Integer>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<Double> al3 = new ArrayList<Double>();
ArrayList<ArrayList<Object>> al4 = new ArrayList<ArrayList<Object>>();
al1.add(1);
al1.add(2);
al1.add(3);
al1.add(4);
al2.add("Hello");
al2.add("how");
al2.add("are");
al2.add("you");
al3.add(100.12);
al3.add(200.34);
al3.add(300.43);
al3.add(400.56);
mainAl.add(al1);
mainAl.add(al2);
mainAl.add(al3);
for (Object obj : mainAl) {
System.out.println(obj);
}
al4.add(mainAl);
for (Object obj : al4) {
System.out.println(obj);
}
}
}
I hope this example is helpful for you.

How do I write foreach loop?

I want to write foreach like this:
for (Object object1 : list1 , Object object2 : list2)
Is it possible?
Write it as nested loop to iterate over all element combinations
for (Object object1 : list1){
for (Object object2 : list2){
...
}
}
or in one iteration with do...while, this is equal to code above.
int i = 0, j = 0;
do {
Object object1 = a.get(i)
Object object2 = b.get(j)
...
if (i == a.size() - 1) j++;
} while (i < a.size() && j < b.size());
You can also merge both lists and then iterate all elements one by one
// Add items to the other list - BEWARE - list1's contens will change
list1.addAll(list2);
for (Object object : list1) {
...
}
Safe way with Guava
Iterable<Object> combined = Iterables.unmodifiableIterable(
Iterables.concat(list1, list2));
for (Object object : combined) {
System.out.println(object);
}
It depends on what you're trying to do.
If you want to iterate 0th to Nth item in both collections being able to work with elements of both in one loop body, you can write something like this:
for(int i = 0;i < list1.size() && i < list2.size();i++) {
Object object1 = list1.get(i);
Object object2 = list2.get(i);
/* your code */
...
}
Note that if one of the collections is smaller than other, additional elements in bigger collection won't be processed.
If you want to iterate list1 and then list2, you can simply create a new one containing previous two:
List<Object> n = new ArrayList<Object>(list1);
n.addAll(list2)
for(Object o : n) {
/* your code */
...
}
Or finally, if you want to iterate list of lists, you can
for(List<Object> il : (List<List<Object>>)list1) {
for(Object o : il) {
/* code for each object in child list */
...
}
/* code for each child list in parent */
...
}
In a single foreach statement you are not allowed to iterate through two collections at the same time. If you want to use only one foreach, you must merge the collections first.
You could do it like this:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String s1 = "string 1";
String s2 = "string 2";
String s3 = "string 3";
String s4 = "string 4";
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add(s1);
list1.add(s2);
list2.add(s3);
list2.add(s4);
List<String> merged = new ArrayList<String>();
merged.addAll(list1);
merged.addAll(list2);
for(String s : merged)
{
System.out.println(s);
}
}
}
it is not possible to write like that but you can use this code instead
i hope if it will help you
String []one={"hello","thanks"};
int[]two={1,2,3};
String item;
int flag;
for(int i=0;i<one.length+two.length;i++){
if(i<one.length){
item=one[i];
System.out.println(item);
}
if(i<two.length){
flag=two[i];
System.out.println(flag);
}
}

Extract String[] elements from a list

at my work I've got the following source code:
import java.util.ArrayList;
import java.util.List;
public class Temporaer
{
public static void main(String[] args)
{
List stringArrayList = new java.util.ArrayList();
stringArrayList.add(fillStringArrayElement("a", "b"));
stringArrayList.add(fillStringArrayElement("c", "d"));
String[] listElement;
/*
* I'm stuck here, because I don't know what I have to do
*/
System.out.println(listElement.length);
}
//Just a method to fill a list easily
private static String[] fillStringArrayElement (String firstElem, String secondElem)
{
String[] stringArrayListElement = new String[2];
stringArrayListElement[0] = firstElem;
stringArrayListElement[1] = secondElem;
return stringArrayListElement;
}
}
My goal is it to extract each list item and work with those.
I tried to use the toArray[T[]) method as mentioned here. Though it generates an java.lang.ArrayStoreException. Note: I cannot change the type of the list because the list is filled by an extern service. Maybe I have to convert the list first...
Can someone show me a way to achive my goal? Thanks in advanced.
Iterator is an interface in java used to iterate over a Collection like ArrayList or other Collection framework classes.
Before reading ArrayList make sure values are available using the size() method.
Here a sample working snippet for your problem.
String [] myArray ;
if (stringArrayList.size()>0){
Iterator<String [] > i = stringArrayList.iterator();
while(i.hasNext()){
myArray = i.next();
for(String s : myArray)
System.out.println(s);
}
}
}
Don't use Raw ArrayList, instead use Generics
Use this:
List<String[]> stringArrayList = new java.util.ArrayList<String[]>();
stringArrayList.add(new String[]{"a", "b"});
stringArrayList.add(new String[]{"c", "d"});
//if you cant to convert the stringArrayList to an array:
String[][] listElement = stringArrayList.toArray(new String[0][]);
for (String[] inArr : listElement){
for (String e : inArr){
System.out.print(e + " ");
}
System.out.println();
}
String[] listElement;
Above statements is incorrect because you are keeping arrays in list so your listElement must contain String[] .
String [][] listElement
Something like below.
listElement=stringArrayList.toArray(new String[stringArrayList.size()][]);

Categories