0

I have a List of List string, now I want to convert it into List of List Integer. Suggest some way, How to proceed for it?

here is my code:

public class convert {

    public static void main(String[] args) {
        try {

            List<List<String>> outerList = new ArrayList<List<String>>();
            outerList.add(new ArrayList<String>(asList("11","2")));
            outerList.add(new ArrayList<String>(asList("2","1")));
            outerList.add(new ArrayList<String>(asList("11","3")));

            System.out.println(outerList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

4 Answers 4

4

I woud suggest using the Streams API for this:

import static java.util.stream.Collectors.toList;

...

integerList = outerList.stream()
   .map(innerList->innerList.stream().map(Integer::valueOf).collect(toList()))
   .collect(toList());
Sign up to request clarification or add additional context in comments.

3 Comments

This also works, can you tell how your appraoch differ from rest of the replies I got. I mean, can use of map add some difference in term of performance.
Main difference is that this is Java 8, while other answers also work with previous versions of Java
The approach differs from others in that it is more concise and more readable because it states the intent rather than going through the mechanics of achieving it. In terms of performance you can expect a very marginal overhead, which is very probably dwarfed by the computation going on in Integer::valueOf.
3

You simply try like this:

for(String s : yourStringList) 
{
  intList.add(Integer.valueOf(s));
}

EDIT

for (List<String> s : yourStringList) {
    List<Integer> x = new ArrayList<Integer>();
    for (String str: s) {
        x.add(Integer.parseInt(str));
    }
    intList.add(x);
}

1 Comment

+1. Maybe enclose in { } and add a little validation in there?
1

You will have to iterate over each subItem of each item.

List<List<String>> stringList = new ArrayList<List<String>>(); // Input
List<List<Integer>> intList = new ArrayList<List<Integer>>(); // Output
for (List<String> item : stringList) {
    List<Integer> temp = new ArrayList<Integer>();
    for (String subItem : item) {
        temp.add(Integer.parseInt(subItem));
    }
    intList.add(temp);
}

Comments

1

res is new arrayList contains lists of integers.

       List<List<Integer>> res = new ArrayList<List<Integer>>();

        for(List<String> l : outerList){
            ArrayList<Integer> al = new ArrayList<Integer>();
            for(String s: l){
                al.add(Integer.valueOf(s));
            }
            res.add(al);
        }

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.