Convert a list of integers into a comma-separated string
Yes. However, there is no Collectors.joining
for a Stream<Integer>
; you need a Stream<String>
so you should map
before collecting. Something like,
System.out.println(i.stream().map(String::valueOf)
.collect(Collectors.joining(",")));
Which outputs
1,2,3,4,5
Also, you could generate Stream<Integer>
in a number of ways.
System.out.println(
IntStream.range(1, 6).boxed().map(String::valueOf)
.collect(Collectors.joining(","))
);
How to split a comma-separated string?
You could do this:
String str = "...";
List<String> elephantList = Arrays.asList(str.split(","));
Basically the .split()
method will split the string according to (in this case) delimiter you are passing and will return an array of strings.
However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the Arrays.asList()
utility. Just as an FYI you could also do something like so:
String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));
But it is usually better practice to program to an interface rather than to an actual concrete implementation, so I would recommend the 1st option.
convert comma separated string to list without intermediate container
If you're using Java 8, you can:
int[] numbers = Arrays.asList(numbersArray.split(",")).stream()
.map(String::trim)
.mapToInt(Integer::parseInt).toArray();
If not, I think your approach is the best option available.
Related Topics
Codility Tape Equilibrium Getting Zero on Some Cases
Autosize Column Width Using Poi
Jsr 303 Validation, If One Field Equals "Something", Then These Other Fields Should Not Be Null
Array Pairwise Matching in Java Give Error Also Store Data Between Two Similar Element
Jdk Tools.Jar as Maven Dependency
How to Mark Cucumber Junit Step as Failed But Continue
Spring JPA Repository: Prevent Update on Save
Method to Find the Smallest Number from an Integer
Prevent Empty Values on String Split
Json to Pojo With Nested Values
How to Disable Fail_On_Empty_Beans in Jackson
Print Out All Possible Combinations of an Arraylist<Arraylist<String>> Recursively
How to Exclude an Android App from Battery Optimization Using Code
When I Run Mockito Test Occurs Wrongtypeofreturnvalue Exception
Filling a List With All Enum Values in Java
Change the Textview Text Color When Button Is Clicked in Android
Bottomnavigationview - How to Avoid Recreation of Fragments and Reuse Them