Preferred Idiom for Joining a Collection of Strings in Java

后端 未结 7 1598
悲哀的现实
悲哀的现实 2020-11-30 11:20

Given a Collection of Strings, how would you join them in plain Java, without using an external Library?

Given these variables:

Collection

        
7条回答
  •  有刺的猬
    2020-11-30 11:38

    Collectors can join Streams which is very useful if you want to filter or map your data.

    String joined = Stream.of("Snap", "Crackle", "Pop")
            .map(String::toUpperCase)
            .collect(Collectors.joining(", "));
    

    To get a Stream from a Collection, call stream() on it:

    Arrays.asList("Snap", "Crackle", "Pop").stream()
    

提交回复
热议问题