input array in String in java

https:/‮‬/www.lautturi.com
input array in String in java

To input an array in a String in Java, you can use the Arrays.toString() method or the String.join() method (Java 8 and later).

Here is an example of how to use the Arrays.toString() method to input an array in a String:

int[] array = {1, 2, 3, 4, 5};
String str = Arrays.toString(array);
System.out.println(str);  // Output: [1, 2, 3, 4, 5]

In this example, the array variable is an array of integers, and the Arrays.toString() method is used to convert it to a String. The resulting String is then printed to the console.

Here is an example of how to use the String.join() method to input an array in a String:

int[] array = {1, 2, 3, 4, 5};
String str = String.join(", ", Arrays.stream(array).mapToObj(String::valueOf).toArray(String[]::new));
System.out.println(str);  // Output: 1, 2, 3, 4, 5

In this example, the array variable is an array of integers, and the Arrays.stream() method is used to convert it to a stream of integers. The stream is then mapped to a stream of String objects using the mapToObj() method and the String::valueOf method reference, and the resulting stream is converted to an array of String using the toArray() method and the String[]::new method reference. The String.join() method is then used to join the elements of the array with a comma and a space as the separator. The resulting String is then printed to the console.

For more information on the Arrays.toString() and String.join() methods in Java, you can refer to the Java documentation and the Java tutorial.

Created Time:2017-11-01 22:29:52  Author:lautturi