How to convert a range to a delimited string in Java 8+

java string join array
convert list to comma separated string java 8
convert integer list to comma separated string java 8
convert set to comma separated string java 8
convert list of long to comma separated string java 8
list to string java 8
string.join java 8
array to string java

How can you convert a range in Java (either using java.util.stream.LongStream or java.util.stream.IntStream) to a delimited string in Java?

I have tried:

String str = LongStream.range(16, 30)
                .boxed()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
System.out.println(str);

This prints:

16,17,18,19,20,21,22,23,24,25,26,27,28,29

The same can be used with IntStream. Is there a more convenient conversion of a range to a delimited string?

Seriously, just for the fun of it. Using guava:

String result = ContiguousSet.create(
                       Range.closedOpen(16, 31), DiscreteDomain.integers())
                             .asList()
                             .toString();

Or

 String result = String.join(",",
            IntStream.rangeClosed(16, 30).mapToObj(String::valueOf).toArray(String[]::new));

Or:

String result = String.join(",",
            () -> IntStream.rangeClosed(16, 31).mapToObj(x -> (CharSequence) String.valueOf(x)).iterator());

Or (seems like I got carried away a bit with this):

String result = IntStream.rangeClosed(16, 31)
            .boxed()
            .collect(
                    Collector.of(
                            () -> new Object() {
                                StringBuilder sb = new StringBuilder();
                            },
                            (obj, i) -> obj.sb.append(i).append(",")
                            ,
                            (left, right) -> {
                                left.sb.append(right.sb.toString());
                                return left;
                            },
                            x -> {
                                x.sb.setLength(x.sb.length() - 1);
                                return x.sb.toString();
                            })
            );

And after Holger's good points, here is even a simpler version:

    StringBuilder sb = IntStream.range(16, 30)
            .collect(
                    StringBuilder::new,
                    (builder, i) -> builder.append(i).append(", "),
                    StringBuilder::append);

    if (sb.length() != 0) {
        sb.setLength(sb.length() - 2);
    }
    String result = sb.toString(); 

Java 8 - Join String Array - Convert Array to String, The return string is received by appending all strings delimited by argument separator. Method Syntax. String join(CharSequence delimiter, CharSequence How can you convert a range in Java (either using java.util.stream.LongStream or java.util.stream.IntStream) to a delimited string in Java?

With IntStream.mapToObj:

String s = IntStream.range(16, 30)
                    .mapToObj(String::valueOf)
                    .collect(Collectors.joining(","));

Convert a List to a Comma-Separated String in Java 8, This tutorial demonstrates how to use streams in Java 8 and Java 7 to convert a list to a comma-separated string by manipulating the string  Convert List to String comma separated Values: Here we will see how to convert a List to String comma separated values using Java 8. Using Java 8 streams and String.join() to convert the list of strings into a comma separated values. Implementing the same using the lower version of java 7 and removing

If your sense of convenience implies less code, there is no need to explicitly map the Long to String. They can be simply mapped while collecting process. Here's the code to do so:

List<String> str = LongStream.range(16, 30)
            .boxed()
            .collect(Collectors.mapping(l -> String.valueOf(l), Collectors.toList()));
System.out.println(str.toString());

The result is:

[16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

In response to the comment to whether boxing should be avoided, it has to happen anyway. The range() in this case returns an object of LongStream which has to be converted to a stream of Long.

According to @Jubobs The mapToObject() effectively returns stream of Long from the LongStream object.

Java program to expand a String if range is given?, Which Java libraries are useful for competitive programming? Input : string x = "​1-5, 8, 11-14, 18, 20, 26-29" Output : string y = "1, 2, 3, 4, 5, 8, 11, 12, 13, in a string using Hashmap · Program to convert List of Integer to List of String in Java​  Convert a List<String> in a String with all the values of the List comma separated using Java 8 is really straightforward. Let’s have a look on how to do that. Java 8 (or above) We simply can write String.join(..), pass a delimiter and an Iterable, then the new StringJoiner will do the rest:

Range extraction, (The range includes all integers in the interval including both endpoints) 35 Icon and Unicon; 36 J; 37 Java; 38 JavaScript o_(rp(list(0, 1, 2, 4, 6, 7, 8, 11, 12​, 14, 15, 16, 17, 18, 19, 20, 21, 22, Although Pascal offers a Str procedure for converting a variable to a text string, maddeningly, it is a procedure  Convert a List to a Comma-Separated String in Java 8 DZone 's Guide to This quick tutorial shows you how to use streams in Java to convert the contents of a list to a comma-separated string in Java 8.

Range expansion, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 31 Icon and Unicon; 32 J; 33 Java; 34 JavaScript Take a comma-delimited string of ranges, and expand it into an array of If necessary, subroutine SPLOT could be re-​written to convert an integer to a digit string without a WRITE statement,  How to convert comma separated string to ArrayList in Java? 1) Using the split method and regular expression (regex) Split string using split method and then convert resulting array to List using the asList method of the Arrays class as given below.

String (Java Platform SE 8 ), All string literals in Java programs, such as "abc" , are implemented as instances of this class. This method does not properly convert bytes into characters. Returns the number of Unicode code points in the specified text range of this String . CharSequence elements joined together with a copy of the specified delimiter  Collectors.joining() is designed with a fluent API, and can be used with Java 8 streams. In Java 8, you can use Collectors.joining() method to join stream of strings (or stream of primitives with their string value). This method internally uses StringJoiner class. 4.1. Join Stream of strings. Java program to join stream of strings in Java 8.

Comments
  • In what sense do you mean the conversion could be convenient?
  • @mark42inbound Can you avoid boxing for example.
  • @gil.fernandes If the sight of boxed annoys you, you can replace .boxed().map(String::valueOf) by .mapToObj(String::valueOf), which feels more idiomatic (to me anyways).
  • @Jubobs .mapToObj(String::valueOf) seems to be a good suggestion
  • we still use guava for some of these things (probably not this one), but still just an example: String result = ContiguousSet.create( Range.closedOpen(16, 31), DiscreteDomain.integers()) .asList() .toString();
  • If you are going to use a manual collector, use the three-arg collect method instead of Collector.of. That way, your approach has a point, as it allows to omit the boxed(), making it more efficient. Then, don’t wrap the StringBuilder into another object; that’s unnecessary: StringBuilder sb = IntStream.range(16, 30) .collect(StringBuilder::new, (b,i)->b.append(i).append(", "), StringBuilder::append); if(sb.length()!=0) sb.setLength(sb.length()-2); String result = sb.toString();
  • @Holger this is how I had it initially in my IDE, what I did not like is that separate setLength... I'll edit good point about the wrapping though!
  • Hmm, the output is a list and not a delimited string.
  • If you want it to be a String simply call the toString() after collecting the elements. It'll work too.