user3086819
user3086819

Reputation: 107

Return certain values from String ArrayList

I have declared List<String> listOfValues = new ArrayList<String>();

It's outputs look like this:

[0.0,100.0,5.0],[1.0,200.0,8.0],[2.0,600.0,2.0],....

So for example, by calling listOFvalues.get(0) I would access 0.0,100.0,5.0

What I'm trying to do is, access and store its column values. So basically I need store 0.0,1.0,2.0 as the first array/arrayList, 100.0,200.0,600.0 as the 2nd and so on.

The problem is, so far, I'm only able to get the whole Row (with listOfValues.get()).

Upvotes: 0

Views: 85

Answers (3)

Raul Guiu
Raul Guiu

Reputation: 2404

You could create your List extending ArrayList and overwriting the get method:

public class ColumnArrayList<T> extends ArrayList<String> {
    public String get(int i) {
        StringBuilder buffer = new StringBuilder();
        String delim = "";
        for(int j=0;j<super.size();j++) {
            buffer.append(delim).append(super.get(j).split(",")[i]);
            delim = ",";
        }
        return buffer.toString();
    }
}

To see it working:

public class Demo {     
    public static void main(String[] args) {
        List<String> listOfValues = new ColumnArrayList<String>();
        listOfValues.add("0.0,100.0,5.0");
        listOfValues.add("1.0,200.0,8.0");
        listOfValues.add("2.0,600.0,2.0");
        System.out.println(listOfValues.get(0));
        System.out.println(listOfValues.get(1));
        System.out.println(listOfValues.get(2));
    }
}

Will print what you want:

0.0,1.0,2.0
100.0,200.0,600.0  
5.0,8.0,2.0

Upvotes: 1

You can use the String method Split to make an array from each String element.

List<String> splittedArray = new ArrayList<>();
for(String s: listOfValues)
{
  for(String ss: s.split(",")) splittedArray.add(ss);
}

Then you can access each element through splittedArray.

Another option is to store the splitted elements into a matrix so they can be accessed as columns:

List<List<String>> matrix = new ArrayList<>();
for(String s: listOfValues)
{
  matrix.add(Arrays.asList(s.split(",")));
}

Upvotes: 3

Devavrata
Devavrata

Reputation: 1795

You can use String class method split().

String temp="0.0,100.0,5.0";
String[] array=temp.split(",");

Upvotes: 0

Related Questions