简体   繁体   中英

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[] = {}.

With this code I use two variable

List<RoomClassRes> roomClassRes and String[] roomClassList

I want to fill String[] with all of name at List<RoomClassRes>

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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