Using list stream: Arbitrary Object List Splice String
- 2021-11-10 09:42:47
- OfStack
Arbitrary Object List Splice String
In the development, the data in List is often processed. One common processing method is splicing. Each element in List is spliced into an String through a specific separator. Before that, we often used the following method:
String. join method
As shown below:
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("d");
stringList.add("k");
System.out.println(String.join(",", stringList));
}
Although this method is very easy to use, it has one defect, that is, the objects in List can only be characters or strings, so if it is other types of data or uncertain types of data, it cannot be directly processed.
Next, introduce a more convenient processing method
As shown below:
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("d");
stringList.add("k");
System.out.println(String.join(",", stringList));
List<Object> objectList = new ArrayList<>();
objectList.add(1L);
objectList.add(10);
objectList.add(" Very convenient ");
System.out.println(objectList.stream().map(Objects::toString).collect(Collectors.joining()));
System.out.println(objectList.stream().map(Objects::toString).collect(Collectors.joining(",")));
System.out.println(objectList.stream().map(Objects::toString).collect(Collectors.joining("-")));
System.out.println(stringList.stream().map(Objects::toString).collect(Collectors.joining("-")));
}
The List stream function can convert any data type into String, and then use Collectors. joining () method to splice elements in any form, which is really a convenient and simple way.
Stream stream merges strings, splices strings
List<String> strings = Arrays.asList("abc", "", "de", "efg", "abcd", "", "jkl");
String mergeString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(","));
System.err.println(" Merge strings : "+mergeString);
Console output
Merge Strings: abc, de, efg, abcd, jkl
.stream
Convert data into an stream stream
.filter
Filter field
Collectors.joining
String Connection Collector (String Splicing)