Skip to content
Advertisement

How to get first parameter from each 2D-array data in android studio using java

I have a String 2D-array named items in my app like this :

    String[][] items = {

            {"(kilogram)","1"},
            {"(gram)","1000"},
            {"(pound)","2.20462262"},
            {"(pound - troy)","2.6792288807"},
            {"(carat)","5000"},
            {"(ounce)","35.2739619"},
            {"(ounce - troy)","32.1507466"},

     }

and I want to have a String ArrayList that include first parameter of each item data, something like this :

ArrayList<String> data = new ArrayList<>();
data = {(kilogram),(gram),(pound),(pound - troy),(carat),(ounce),(ounce - troy)}

i used this code but unfortunately it didn’t work

    ArrayList<String> data = new ArrayList<>();

    for (int i = 0; i <= items.length;) {
        data.add(items[i][0]);
        i++;
    }

Advertisement

Answer

You can also use streams to build this list:

List<String> data = Stream.of(items)
        .map(item -> item[0])
        .collect(Collectors.toList());

If you still want to use a for loop go with (use < instead of <=):

for (int i = 0; i < items.length; i++) {
    data.add(items[i][0]);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement