java 8 lamda 连接 数组或list为字符串
今天是:
我需要三件东西:爱情友谊和图书。然而这三者之间何其相通!炽热的爱情可以充实图书的内容,图书又是人们最忠实的朋友。
User Image java 8 lamda 连接 数组或list为字符串 2019-11-16

java8 对于字符串的连接很方便,使用lamda 可以对于字符串的连接更加简洁和方便

1.Api

    

  • joining

    public static Collector<CharSequence,?,String> joining()

    返回一个 Collector ,将输入元素连接到一个 String ,按照顺序。

    结果

    一个 Collector ,将输入元素连接到一个 String中,按照顺序

  • joining

    public static Collector<CharSequence,?,String> joining(CharSequence delimiter)

    返回一个 Collector ,以遇到的顺序连接由指定的分隔符分隔的输入元素。

    参数

    delimiter - 要在每个元素之间使用的分隔符

    结果

    Collector ,它以相遇顺序连接由指定的分隔符分隔的CharSequence元素

  • joining

    public static Collector<CharSequence,?,String> joining(CharSequence delimiter,
                                                           CharSequence prefix,
                                                           CharSequence suffix)

    返回一个 Collector ,以按照顺序将指定的 Collector分隔的输入元素与指定的前缀和后缀相连接。

    参数

    delimiter - 要在每个元素之间使用的分隔符

    prefix - 在连接结果开始时使用的字符序列

    suffix - 连接结果末尾要使用的字符序列

    结果

    一个 Collector ,它以相遇的顺序连接由指定的分隔符分隔的CharSequence元素

2. 实例    

public class Joining {

    public static String ArrayJoin(String[] arr){
        return Arrays.stream(arr).collect(Collectors.joining("','","'","'"));
    }

    public static String ListJoin(List<String> list){
        return list.stream().collect(Collectors.joining(","));
    }

    public static String CharJoin(List<CharSequence> charList){
        return charList.stream().collect(Collectors.joining());
    }
}
public class LamdaJoining {

    @Test
    public void testArrayJoining(){
        String[]  helloWorld = new String[]{"H","e","l","l","o"," ","W","o","r","l","d","!"};
        System.out.println(Joining.ArrayJoin(helloWorld));
    }

    @Test
    public void testListJoining(){
        List<String> helloWorld = Arrays.asList("H","e","l","l","o"," ","W","o","r","l","d","!");
        System.out.println(Joining.ListJoin(helloWorld));
    }

    @Test
    public void testCharSequenceJoining(){
        List<CharSequence> helloWorld = Arrays.asList("H","e","l","l","o"," ","W","o","r","l","d","!");
        System.out.println(Joining.CharJoin(helloWorld));
    }
}

          output:

'H','e','l','l','o',' ','W','o','r','l','d','!'

H,e,l,l,o, ,W,o,r,l,d,!

Hello World!

 

分享到:

我的

类型标签

外部链接

网站访问总量