6

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.

Adam Hughes
  • 14,601
  • 12
  • 83
  • 122

3 Answers3

20

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

String result = list.stream().skip(1).collect(Collectors.joining(""));
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
4
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.

atao
  • 835
  • 6
  • 13
1

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);
Ján Яabčan
  • 743
  • 2
  • 10
  • 20