Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<List<String>> to ArrayList<String> in Android

I want to convert them to ArrayList and I will store them. After that, I have to convert them into old values. Do you have any suggestions? Thanks in advance.

public List<List<String>> phones = new ArrayList<>();
public List<List<Restaurant.Menu>> menus = new ArrayList<>(); 

public ArrayList<String> phones = ?
public ArrayList<String> menus = ?
like image 603
ozo Avatar asked Jan 28 '26 17:01

ozo


1 Answers

For the first scenario, you can flatten the phones nested list into a single list and then collect into an ArrayList.

ArrayList<String> result = 
                  phones.stream()
                        .flatMap(Collection::stream)
                        .collect(Collectors.toCollection(ArrayList::new));

For the second scenario, you will need to extract the string representation of the Menu objects given you've overridden toString, otherwise you'll need to extract some type of property from the Menu objects in order to project from Menu to String.

Given you've overridden toString, then do it this way:

ArrayList<String> menuResult = 
                  menus.stream()
                       .flatMap(Collection::stream)
                       .map(Menu::toString)
                       .collect(Collectors.toCollection(ArrayList::new));

Given you need to extract some property from menus, then do it this way:

ArrayList<String> menuResult = 
                  menus.stream()
                       .flatMap(Collection::stream)
                       .map(Menu::getName)
                       .collect(Collectors.toCollection(ArrayList::new));

If your API level doesn't support these features then you can use:

// flatten List<List<String>> to ArrayList<String>
ArrayList<String> phonesAccumulator = new ArrayList<>();
for (List<String> temp : phones) {
     phonesAccumulator.addAll(temp);
}

// flatten List<List<Restaurant.Menu>> to ArrayList<String>
ArrayList<String> menusAccumulator = new ArrayList<>();
for (List<Restaurant.Menu> temp : menus) {
    for(Restaurant.Menu m : temp){
       menusAccumulator.add(m.toString());
       // or m.getName();
    }
}
like image 58
Ousmane D. Avatar answered Jan 31 '26 07:01

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!