转换列表<list <string>&gt;到Android中的ArrayList <string>

时间:2017-12-31 10:47:48

标签: java android list arraylist type-conversion

我想将它们转换为ArrayList,我会存储它们。在那之后,我必须将它们转换为旧值。你有什么建议吗?提前谢谢。

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

public ArrayList<String> phones = ?
public ArrayList<String> menus = ?

4 个答案:

答案 0 :(得分:1)

对于第一种情况,您可以将手机嵌套列表展平为一个列表,然后收集到ArrayList

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

对于第二种情况,您需要提取Menu对象的字符串表示,只要您覆盖toString,否则您需要从{{{{}}中提取某种类型的属性。 1}}对象,以便从Menu投射到Menu

鉴于您已覆盖String,请按以下方式执行:

toString

鉴于你需要从菜单中提取一些属性,然后这样做:

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

如果您的API级别不支持这些功能,则可以使用:

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

答案 1 :(得分:0)

如果你使用的是Java 8,那么flatMap在这里很有用:

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

答案 2 :(得分:0)

我正在证明我的解决方案如下所述,所以你可以根据你自己的方式进行改变 -

var
   clientScreenScale   : Single;
   clientScreenSize    : TSize;
   clientScreenService : IFMXScreenService;
begin
  if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(clientScreenService)) then
  begin
    clientScreenScale   := clientScreenService.GetScreenScale;
  end
  else clientScreenScale   := 1;

  // The display device's width:
  clientScreenSize.CX   := Round(clientScreenService.GetScreenSize.X*clientScreenScale);

  // The display device's height:
  clientScreenSize.CY   := Round(clientScreenService.GetScreenSize.Y*clientScreenScale);
end;

甜蜜,简单且可替换的格式,在Java 6+之后兼容,

希望这对你有所帮助,谢谢。

答案 3 :(得分:0)

我用gson来解决它。我分享了一个样本。

Gson gson = new Gson();
ArrayList<String> gsonString = new ArrayList<>();
for(int i=0; i<restaurants.size(); i++)
        gsonString.add(gson.toJson(restaurants.get(i)));
// Store it
tinydb.putListString("tinyRestaurant",gsonString);

再次转换

Gson gson = new Gson();
for(int i=0; i<tinydb.getListString("tinyRestaurant").size(); i++)
            restaurants.add(gson.fromJson(tinydb.getListString("tinyRestaurant").get(i), Restaurant.class));