Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join all but first elements in a list to string

Tags:

java

Following this thread on how to join a list into a String,

I'm wondering what the most succinct way to drop an element from the list and then join the remaining list. For example, if my list is:

[a, b, c, d]

and I want the String:

"bcd"

How could I most succinctly drop a and then join the remaining elements? I'm new to Java, and my solutions feel heavy-handed.

like image 268
Adam Hughes Avatar asked Dec 23 '15 16:12

Adam Hughes


People also ask

How to Join elements of a list into a string in Python?

If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() . It can be written as a generator expression, a generator version of list comprehensions.

How to Join only two elements in a list Python?

Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.

How to Join indexes in a list Python?

To join a list in Python, there are several ways in Python. Using + operator to join two lists. Appending one list item to another using the list append() method. Using the list extend() method to add one list's elements to another.


3 Answers

If you're using java8 I like using streaming and the available collectors:

String result = list.stream().skip(1).collect(Collectors.joining(""));
like image 94
Reut Sharabani Avatar answered Sep 28 '22 08:09

Reut Sharabani


String[] data = {"a", "b", "c", "d"};
String[] f = Arrays.copyOfRange(data, 1, 4);
String r = Arrays.toString(f).substring(1).replaceAll("\\]$", "").replaceAll(", ", "");

It does the job with Java 6 and without any library.

like image 38
atao Avatar answered Sep 28 '22 09:09

atao


if you want to drop another element like first, or more elements ,you can do it with filter. It is very universal way in my opinion.

    String [] array = {"a","b","c","d", "a"};
    List<String> list = Arrays.asList(array);
    String result = list.stream().filter(element -> !element.equals("a")).collect(Collectors.joining(","));
    String result2 = Arrays.stream(array).filter(element -> !element.equals("a")).collect(Collectors.joining(","));

    System.out.println(result);
    System.out.println(result2);
like image 32
Ján Яabčan Avatar answered Sep 28 '22 09:09

Ján Яabčan