Monday, 8 January 2018

How to convert a primitive char array into a List


Arrays.asList()  only taking objects and convert them into a list; however primitive types, like char,  are not considered instances.

char[] chars = "I hate it".charArray();
List charList = Arrays.asList(chars);

char array is an object instance. so, here charList is a collection to hold a single array object, but not individual chars.

I didn't find a clever way, but having to convert a single char into its wrapper and then collect them into a collection.


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author YNZ
 */
public class ConvertPrimArrayIntoList {

    public static void main(String[] args) {

        //a primitive array
        char[] chars = "I hate it. ".toCharArray();
        

        //
        List charList = new ArrayList<>();
        for (char c : chars) {
            charList.add(c);
        }

        System.out.println("size of charList " + charList.size());
        
        //in java 8
        String str = "what is happening? ";
        List listOfChar = str.chars().mapToObj(c -> new Character((char) c)).collect(Collectors.toList());
        System.out.println("List chars : " + listOfChar);

    }

}



No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...