Convert long [] to String using Java 8 threads

I want to convert a primitive long array, for example, long[] l1 = { 1, 2, 3, 4 };to String. This string must have each of these values ​​separated by a character ,.

I want to achieve this using Java 8 threads. I already got this working for an array Long[], but for some reason I can't get this to work for the primitive Long[].

public static void main(String[] args) {
    long[] l1 = { 1, 2, 3, 4 };
    Long[] l2 = new Long[4];
    l2[0] = new Long(1);
    l2[1] = new Long(2);
    l2[2] = new Long(3);
    l2[3] = new Long(4);
    System.out.println(longToString(l2));
}

public static String longToString(Long... l) {
    String[] x = Arrays.stream(l).map(String::valueOf).toArray(String[]::new);
    String y = Arrays.stream(x).collect(Collectors.joining(","));
    return y;
}

How can I do this work for longToString(long... l)instead longToString(long... l)?

In addition: did I manage to find the best way to convert it, or can it be simplified? I am new to Java 8 thread functions.

+4
source share
2 answers

:

long[] arr = { 1, 2, 3, 4 };
Arrays.stream(arr).mapToObj(l -> ((Long) l).toString()).collect(Collectors.joining(","))

, Arrays.stream(long[]) LongStream, Stream<Long>, mapToObj(), Stream<String> .

, String.valueOf() Long.toString(), . String.valueOf , Long String.valueOf :

Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(","))

boxed() Arrays.stream(long[]), Stream<Long>, map():

Arrays.stream(arr).boxed().map(String::valueOf).collect(Collectors.joining(","))
+6

long[] long[].

public static String longToString(long[] primitiveArray) {
    Long[] boxedArray = Arrays.stream(primitiveArray).boxed().toArray(size -> new Long[size]);
    return longToString(boxedArray);
}

, , Arrays.toString, @alfasin .

0

Source: https://habr.com/ru/post/1611125/


All Articles