This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Practical tip 3: String and container interchange

A practical trick every day: string and Collection translation

The business scenario of converting a string to a List is very, very common, and fairly simple to implement

public List<String> str2list(String str, String split) {
    String[] cells = str.split(split);
    return Arrays.asList(cells);
}
Copy the code

So what else is there besides the above implementation?

I. String transfer list

The above posture is equivalent to the string to the array, and then through the array to the list, so you can use the previous word group to the list of several ways

1. JDK support

This is implemented with Collections. AddAll

public List<String> str2list2(String str, String split) {
    List<String> list = new ArrayList<>();
    Collections.addAll(list, str.split(split));
    return list;
}
Copy the code

What if I want to convert it to an int list? This can be done in the following way

public List<Integer> str2intList(String str, String split) {
    returnStream.of(str.split(split)) .map(String::trim) .filter(s -> ! s.isEmpty()) .map(Integer::valueOf).collect(Collectors.toList()); }Copy the code

Convert the array directly to a stream, and then convert it to an int list based on the jdK8 feature

2. Guava

Introduction of depend on

<! -- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1 the jre</version>
</dependency>
Copy the code

In addition to using the JDK native way, with the aid of Guava is also very common case, mainly through Splitter to achieve, writing looks very beautiful

public List<String> str2list2(String str, String split) {
    return Splitter.on(split).splitToList(str);
}
Copy the code

It’s a straightforward one-line code, or if we want to specify the type of list that we output, we can do it as follows

public List<Integer> str2intListV2(String str, String split) {
    returnSplitter.on(split).splitToStream(str) .map(String::trim).filter(s -> ! s.isEmpty()) .map(Integer::valueOf).collect(Collectors.toList()); }Copy the code

3. apache-commons

Introduction of depend on

 <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>
Copy the code

The above stream way is very good, but notice that it has JDK version restrictions, although now is basically 1.8 above the environment for development, but also do not exclude the ancient code, such as my current hand project, Spring or 3…

If we can’t use a stream, is there an easy way to convert a string to a list of a given type?

public List<Integer> str2intListV3(String str, String split) {
    List<Integer> result = new ArrayList<>();
    CollectionUtils.collect(Arrays.asList(str.split(split)), new Transformer<String, Integer>() {
        @Override
        public Integer transform(String s) {
            return Integer.valueOf(s);
        }
    }, result);
    return result;
}
Copy the code

New Transformer(){} (){} (){} (){} (){} (){} (); For example, the above change into jdK8 writing method, directly simplified to

public List<Integer> str2intListV3(String str, String split) {
    List<Integer> result = new ArrayList<>();
    CollectionUtils.collect(Arrays.asList(str.split(split)), Integer::valueOf, result);
    return result;
}
Copy the code

II. List transfer string

1. StringBuilder

The most obvious one is to use StringBuilder directly for concatenation

public String list2str(List<String> list, String split) {
    StringBuilder builder = new StringBuilder();
    for (String str: list) {
        builder.append(str).append(split);
    }
    return builder.substring(0, builder.length() - 1);
}
Copy the code

Two points to note:

  • Use StringBuilder instead of StringBuffer (why?)
  • Pay attention to the last splice symbol

2. String.join

A simpler implementation is as follows

public String list2str2(List<String> list, String split) {
    return String.join(split, list);
}
Copy the code

The downside to this one, of course, is that the list has to be a list of strings, not an int list

3. gauva

Guava also provides a simple way to turn a list into a String, and there are no restrictions on the list type

public <T> String list2str3(List<T> list, String split) {
    return Joiner.on(split).join(list);
}
Copy the code

III. The summary

If there are more advanced custom scenarios, such as non-string class tables, and if there are more advanced custom scenarios, such as non-string class tables, Consider Guava’s Splitter/Joinner

In the above implementation, several interesting programming approaches are also provided

  • Stream: Stream, which is very common after JDK8
  • Function method, callback writing method case

Series of blog posts

  • Practical tips 1: string placeholder replacement -JDK version
  • Practical tips 2: Array and list inter-transfer

II. The other

1. A gray Blog:liuyueyi.github.io/hexblog

A gray personal blog, record all study and work in the blog, welcome everyone to visit

2. Statement

The above content is not as good as the letter, purely the words of a family, due to the limited personal ability, there are inevitably omissions and mistakes, such as found bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Micro-blog address: small gray Blog
  • QQ: A gray /3302797840
  • Wechat official account: a gray blog