Wednesday, October 25, 2017

Java: Convert List to primitive Array long[] ; and primitive Array long[] to List

For instance, you have a list of Long object.

        List<Long> list = <your list>;

You want to convert it to a long[].

1. Java 8
 
        Convert the list to a Stream<Long>, map each Long object to long, and then convert the result to an array.

        long[] array = list.stream().mapToLong(Long::longValue).toArray();

2. Before Java 8 versions

        Created an empty array with the size of your list, loop through the list and add each element to the array.

         long [] array = new long[list.size()];
         int i = 0;
         for (long element : list) {
                 array[i++] = element;
         }

Now you have a long[] array2 object and you want to convert it to a List<Long> object.

3. Java 8

        List<Long> list2 = Arrays.stream(array2).boxed().collect(Collectors.toList());

4. Before Java 8 versions.

        List<Long> list2 = new ArrayList<>();
        for (long value : array2) {
                list2.add(new Long(value));
        }

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

                        
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