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.
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.
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.
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.
If you're using java8 I like using streaming and the available collectors:
String result = list.stream().skip(1).collect(Collectors.joining(""));
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With