Friday, December 15, 2017

java 8: Convert a Long number list to a boxed and unboxed primitive array / convert a String list to String array by Stream

To convert a Long list to array, while Long[] ar = list.stream().toArray(size -> new Long[size]) is perfectly fine, long[] par = list.stream().toArray(size -> new long[size]) does not work. The argument of the toArray method, the IntFunction, takes an parameter type that is bound to Object, and long is not an Object while Long is.

The workaround is to map each element in the Stream to a Long so that when the toArray method without argument is called, it returns an long[] instead of an Object[].

import java.util.List;
import java.util.Arrays;

public class StreamListToArray {
    public static void main(String[] args){
        List<Long> list = Arrays.asList(new Long(11238), new Long(55444), new Long(1099886));
       
        Long[] ar = list.stream().toArray(size -> new Long[size]);
        for(Long lg : ar){
            System.out.println(lg);
        }
        System.out.println();

        //Method 1
        long[] ars = list.stream().mapToLong(Long :: new).toArray();
        for(Long lg : ars){
            System.out.println(lg);
        }
        System.out.println();

        //Method 2
        long[] par = list.stream().mapToLong(Long :: longValue).toArray();
        for(long lg : par){
            System.out.println(lg);
        }

        System.out.println();
        List<String> slist = Arrays.asList("String line 1", "String line 2", "String line 3");
       
        String[] sar = slist.stream().toArray(size -> new String[size]);
        for(String s : sar){
            System.out.println(s);
        }
    }
}

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment