Search code examples
javaarrayslistobjectretrofit2

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.


Solution

  • 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 need to provide the size of the array like in the above function.