2

I have an Integer ArrayList(mainList) which will have Integer Arrays(subList) inside it, I am trying to add integer array elements to mainList and display them at a later time. Adding subLists to mainList and display all elements from subList.

2 subLists = {1,2,4},{3,2,1}
mainList =[{1,2,4},{3,2,1}]
Display : 1,2,4,3,2,1
  1. How to easily retrieve elements from mainList
  2. How to add subLists at a time without looping

The following is the way I am trying to add subLists to mainList

//Adding elements
 ArrayList<ArrayList<Integer>> mainList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> subList = new ArrayList<Integer>();
for(int i=0;i<10;i++) {
    for(int j=i+1;j<10;j++){
        //Do something and add elements to subList
        subList.add(element[j]) }
        mainList.add(subList);

        // When I clear subList mainList is also getting cleared. I want to add the elements of subList to mainList. I was able to do it with loops but how to do this way
        subList.clear();
    }

    //Printing, How do I get the elements from mainList which will have subLists
    for(Integer i:mainList){ 
        System.out.println(i);
    }
}
5
  • 5
    ArrayList<Integer><ArrayList<Integer>> mainList = new ArrayList<ArrayList<Integer>>(); how did this compile? Commented Mar 2, 2017 at 21:49
  • The code shared is syntactically wrong and won't compile. Commented Mar 2, 2017 at 21:50
  • ArrayList<Integer><ArrayList<Integer>> is not compilable. You'd do better to use List as the declared type: List<List<Integer>> mainList = new ArrayList<>();. Likewise for(Integer i:mainList) is not compilable (and should have one blank on either side of the :) because the element type of mainList is not Integer. You can only get the element type of the List you're iterating. You will need to nest a subList loop inside your mainList loop. Names should reflect the domain, not the implementation. Commented Mar 2, 2017 at 21:51
  • When you put an object into an arraylist, you are storing the reference to the object. You can't then reuse the object for another list without altering it for the first list. What you need to do is create a new sublist for each instance you need to add one to an arraylist. Commented Mar 2, 2017 at 21:53
  • @Jason Is there a better way to add the elements of subList to mainList without creating new instances everytime. I am trying to use the same subList Object for each iteration. 1. Add subList elements to mainList 2. clear subList elements 3. Add elements to subList. Goto Step 1 Commented Mar 4, 2017 at 20:48

4 Answers 4

2

Your code

ArrayList<Integer><ArrayList<Integer>> mainList = new ArrayList<ArrayList<Integer>>(); 

doesn't compile, see my edit in below code:

import com.sun.deploy.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> mainList = new ArrayList<ArrayList<Integer>>();

        Integer[] sub1 = {1,2,4};
        Integer[] sub2 = {3,2,1};
        ArrayList<Integer> subList1 = new ArrayList<>(Arrays.asList(sub1));
        ArrayList<Integer> subList2 = new ArrayList<>(Arrays.asList(sub2));

        mainList.add(subList1);
        mainList.add(subList2); //[[1, 2, 4], [3, 2, 1]]


        ArrayList<Integer> intValues = new ArrayList<>();
        for(ArrayList<Integer> inner: mainList){
            intValues.addAll(inner); // add inner list elements to Integer list
        }

        List<String> strings =  intValues.stream().map(Object::toString)
                .collect(Collectors.toList());  // converts to string list

        System.out.println(StringUtils.join(strings, ","));  // prints comma separated string
    }
}

Output:

1,2,4,3,2,1

My explanation is in the code comments.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your time. As per my understanding, you used Java 8 streams to convert the Integer elements to Strings, in this case we don't have to convert to String. We can simply loop through the elements and display them using the below code. for(ArrayList<Integer> i:mainList) for(Integer j:i) System.out.print(j); Having said that, I have also tried using your code to learn the process of applying map to streams. It is not working for me. Can you explain what you are trying to do in map method, I see that you are trying to convert Object to String
1

So, you have an array list, of an array list, of integers. mailList is an array list of subList. subList is an array list of Integers. So, to get one element you would have to get a get. I'll show you.

ArrayList temp = mailList.get(i);
temp.get(j);

So, using the advanced for loop, you would do this to access every element.

for(ArrayList i:mailList)
    for(Integer j:i)
        System.out.print(j);

That code would print all Integers in the 2D array list. I'll now code it with a normal for loop.

for(int i = 0; i < mailList.length; i++){
    ArrayList subList = mailList.get(i);
    for(int j = 0; j < subList.length; j++){
        System.out.print(subList.get(j));
    }
}

That code would do the exact same thing.

So, summary, you get the array list from the array list of array lists, then you get the integer from the array list that you got from the array list of array lists. Hope this helps! :)

(Yes, I know the array-list-ception is kind of confusing, but it's the only way I can think of to explain)

1 Comment

I like these approaches of printing the elements from the Arraylists. Thank you.
0

I have a solution!

class Main {

    public static void main(String[] args) {

        ArrayList < ArrayList < Integer >> mainList = new ArrayList < ArrayList < Integer >> ();

        ArrayList < Integer > subList = new ArrayList < Integer > ();

        for (int i = 0; i < 10; i++) {

            subList = new ArrayList < Integer > ();

            for (int j = i + 1; j < 10; j++) {
                subList.add(element[j])
            }
            mainList.add(subList);
        }

    }
}

Comments

0

Here is a generic solution to build an ArrayList of hetergeous ArrayList such as one might encounter in a SQL Query result set.

package com.mwycombe.arraylistdatatest;

import java.util.ArrayList;

/**
 *
 * @author MWycombe
 */
public class ArrayListDataTest {
    ArrayList<Object> tableData;
    public ArrayListDataTest(){
        int i, j;
        // set up trasnposed table of data
        tableData = new ArrayList<>();
        // set up 6 rows with 3 cols - each column is the same.
        ArrayList<Integer> col1 = new ArrayList<>();
        ArrayList<String> col2 = new ArrayList<>();
        ArrayList<Float> col3 = new ArrayList<>();
        // how build 6 arbitrayr entries for each column and add to the tableData array list
        for (i = 0; i < 6; i++){
            col1.add(i );
            col3.add((float)i + i/10);
        }
        for (i = 0; i < 6; i++) {
            col2.add(String.valueOf(i));
        }
        tableData.add(col1);
        tableData.add(col2);
        tableData.add(col3);
        System.out.println ("Array lists built.");
        System.out.println ("Size tableData, col1, col2, col3");
        //print out class of each column - 1st row entry cell
        for (i=0; i<3; i++){
            System.out.println("Col type " + i + " " + getColumnClass(i));
        }
    }
    private Class getColumnClass(int c){
        System.out.println("Which col? " + c);
        return getValueAt(0,c).getClass();
    }
    private Object getValueAt(int row, int col) {
        System.out.println(("in getValue row: " + row + " col: " + col));
        return ((ArrayList)(tableData.get(col))).get(row);
    }
    public static void main(String[] args) {
        ArrayListDataTest aldt = new ArrayListDataTest();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.