2

I am having trouble finding how to easily build a string from an arrayList of Integer with Java 8, just like this :

[3, 22, 1, 5] to "3 22 1 5"

For the moment I tried :

List<Integer> ids = new ArrayList<Integer>();
/* ... */
String.join(" ", ((ArrayList<String>)(ids))); //cast do not work

List<Integer> ids = new ArrayList<Integer>();
/* ... */
String.join(" ", ids.forEach(id -> Integer.toString(id))); //forEach returns void so it throws an error

Anyone does have a convenient/elegant solution ?

Thanks anyone & have a nice day

0

6 Answers 6

6

You can do this using Streams

List<Integer> ids = new ArrayList<Integer>();
/* ... */
String joined= ids.stream()
                   .map(i -> i.toString())
                   .collect(Collectors.joining(" "));
Sign up to request clarification or add additional context in comments.

Comments

3

Strings are immutable.. You can't append element to it

In this case, i would use StringBuilder

With StringBuilder you can append element :

    int[] myArr = {4,3,4,53,2};
    StringBuilder myStringB = new StringBuilder();
    String myString = new String();

    for (int i : myArr) {
        myStringB.append(i);
    }

    myString = myStringB.toString();

1 Comment

Instead of StringBuilder we can use StringJoiner which automatically places delimiter (here space) between added elements. Demo: ideone.com/onybOm
1

You were almost ready with the solution, just that you need to supply the proper arguments.

If you look at the public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) method signature it takes a delimiter and an iterable. You were almost close to joining the strings using this method, all you had to do is to provide an Iterable<String>.

Since you start with a List<Integer> you need to convert it to an Iterable<String> to do that you can use the below code:

Iterable<String> iterable = ids.stream().map(String::valueOf).collect(Collectors.toList());

Where ids is a List<Integer>. Note that you need to do a map(String::valueOf) as you start with a List<Integer> not with a List<String>. Now that you have an Iterable<String> you can use that as the second argument of String.join().

So the complete solution is:

List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);

Iterable<String> iterable = ids.stream().map(String::valueOf).collect(Collectors.toList());
String result = String.join(" ", iterable);
System.out.println(result);

Output:

1 2 3

If the ids may contain null then you can filter it out before applying the map():

Iterable<String> iterable = ids.stream()
                               .filter(Objects::nonNull)
                               .map(String::valueOf)
                               .collect(Collectors.toList());

Comments

1

If you do not want to use StringBuilder then you can you the following simple for loop:

    List<Integer> ids = new ArrayList<Integer>();
    ids.add(3);
    ids.add(22);
    ids.add(1);
    ids.add(5);

    String st = "";

    for(int i = 1; i <= ids.size(); i++) {
        st += String.valueOf(ids.get(i-1));
        if(i != ids.size()) {
            st += " ";
        }
    }

    System.out.println(st);

Comments

1

If performance matters for you or if you have a very large list I would recommend using a StringBuilder and Java Streams to collect all numbers:

String joined = ids.stream()
        .collect(StringBuilder::new, 
                (s, i) -> s.append(" ").append(i), 
                (s1, s2) -> s1.append(" ").append(s2))
        .substring(1);

This prepends a " " to all numbers. To get the final result we can use StringBuilder.substring() to cut off the first white space.

To improve the performance on large lists you can also use List.parallelStream() or Stream.parallel() to create a parallel stream.

Comments

0

Try this

String numberString = ids.stream().map(String::valueOf).collect(Collectors.joining(" "));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.