简体   繁体   English

Java将对象类列表转换为字符串[]

[英]Java Convert List of Object Class to String[]

I have class named RoomClassRes that have getter&setter id, name, etc and in my main class I declare String[] = {}. 我有一个名为RoomClassRes的类,它具有getter&setter id,名称等,在主类中,我声明String [] = {}。

With this code I use two variable 有了这段代码,我使用了两个变量

List<RoomClassRes> roomClassRes and String[] roomClassList List<RoomClassRes> roomClassResString[] roomClassList

I want to fill String[] with all of name at List<RoomClassRes> 我想用List<RoomClassRes>所有name填充String[]

This doesn't work for me 这对我不起作用

@Override
        public void onResponse(Call<List<RoomClassRes>> call, Response<List<RoomClassRes>> response) {
            List<RoomClassRes> roomClassRes = response.body();

            // 1
            Object[] roomClassObj = roomClassRes.toArray();
            for (int i = 0; i < roomClassObj.length; i++){
                RoomClassRes roomClass = (RoomClassRes)roomClassObj[i];
                roomClassList[i] = roomClass.getName();
            }

            // 2
            int i = 0;
            for(RoomClassRes rc : roomClassRes){
                roomClassList[i] = rc.getName();
                i++;
            }

        }

Nothing works. 什么都没有。

With Java 8. Here you can use the stream API, first get the stream of RoomClassRes then map each room to its name and tranform to array. 使用RoomClassRes 。在这里,您可以使用流API,首先获取RoomClassRes的流,然后将每个房间映射到其名称,然后转换为数组。

public String[] toStringArray(List<RoomClassRes> rooms) {
    return rooms.stream()
            .map(RoomClassRes::getName)
            .toArray(String[]::new);
}

With Java 7. First create the array with the list size, then fill the array and return. 使用Java7。首先创建具有列表大小的数组,然后填充数组并返回。

public String[] toStringArray(List<RoomClassRes> rooms) {
    String[] result = new String[rooms.size()];
    for (int index = 0; index < rooms.size(); index++)
        result[index] = rooms.get(index).getName();
    return result;
}

Note that you cannot declare the array like String[] result = {} because that would create an empty array, you new to provide the size of the array like in the above function. 请注意,您不能像String[] result = {}那样声明数组,因为那样会创建一个空数组,您可以像上面的函数中那样提供新的数组大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM