Java8-如何將List轉變爲逗號分隔的字符串

轉自:https://blog.csdn.net/benjaminlee1/article/details/72860845

Converting a List to a String with all the values of the List comma separated in Java 8 is really straightforward. Let’s have a look how to do that.

在Java 8中將集合List轉變爲用逗號分隔的String是非常簡單的,下面讓我看看如何做到

In Java 8

We can simply write String.join(..), pass a delimiter and an Iterable and the new StringJoiner will do the rest:

我們使用String.join()函數,給函數傳遞一個分隔符合一個迭代器,一個StringJoiner對象會幫助我們完成所有的事情

List<String> cities = Arrays.asList("Milan", 
                                    "London", 
                                    "New York", 
                                    "San Francisco");
String citiesCommaSeparated = String.join(",", cities);
System.out.println(citiesCommaSeparated);
//Output: Milan,London,New York,San Francisco
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

If we are working with stream we can write as follow and still have the same result:

如果我們採用流的方式來寫,就像下面這樣,仍然能夠得到同樣的結果

String citiesCommaSeparated = cities.stream()
                                    .collect(Collectors.joining(","));
System.out.println(citiesCommaSeparated);
//Output: Milan,London,New York,San Francisco
Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing "joining".
  • 1
  • 2
  • 3
  • 4
  • 5

In Java 7

For old times’ sake, let’s have a look at the Java 7 implementation:

由於老的緣故,讓我們看看在java 7中如何實現這個功能

private static final String SEPARATOR = ",";
public static void main(String[] args) {
  List<String> cities = Arrays.asList(
                                "Milan", 
                                "London", 
                                "New York", 
                                "San Francisco");
  StringBuilder csvBuilder = new StringBuilder();
  for(String city : cities){
    csvBuilder.append(city);
    csvBuilder.append(SEPARATOR);
  }
  String csv = csvBuilder.toString();
  System.out.println(csv);
  //OUTPUT: Milan,London,New York,San Francisco,
  //Remove last comma
  csv = csv.substring(0, csv.length() - SEPARATOR.length());
  System.out.println(csv);
  //OUTPUT: Milan,London,New York,San Francisco
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

As you can see it’s much more verbose and easier to make mistakes like forgetting to remove the last comma. You can implement this in several ways—for example by moving the logic that removes the last comma to inside the for-loop—but no implementation will be so explicative and easy to understand as the declarative solution expressed in Java 8.

正如你所看到的,這種方式更加囉嗦並且更加容易犯諸如忘記去除最後一個逗號之類的錯誤。你能夠採用幾種方式來完成這一功能-例如你可以將刪除最後一個逗號的操作邏輯放到for循環中,但是沒有一種實現方式向java 8中如此可解釋性並且容易理解

Focus should be on what you want to do—joining a List of String—not on how.

注意力應該放到你想做什麼-連接List結合,而不是怎樣做

Java 8: Manipulate String Before Joining

If you are using Stream, it’s really straightforward manipulate your String as you prefer by using map() or cutting some String out by using filter(). I’ll cover those topics in future articles. Meanwhile, this a straightforward example on how to transform the whole String to upper-case before joining.

Java 8: 在連接之前操作字符串

如果你使用流,使用map函數或者用於刪掉一些字符串的filter函數能夠更加直觀的操作字符串。我在將來的文章中會覆蓋這些主題。同時,這也是一個直觀展示如何將整個字符串在連接之前轉爲大寫的例子。

Java 8: From List to Upper-Case String Comma Separated

將List集合轉爲大寫的用逗號分隔的String

String citiesCommaSeparated = cities.stream()
                                    .map(String::toUpperCase)
                                    .collect(Collectors.joining(","));
//Output: MILAN,LONDON,NEW YORK,SAN FRANCISCO
If you  want to find out more about stream, I strongly suggest this cool video from Venkat Subramaniam.
  • 1
  • 2
  • 3
  • 4
  • 5

Let’s Play 
The best way to learn is playing! Copy this class with all the implementations discussed and play with that. There is already a small test for each of them.

讓我們嘗試一下。最好的學習方式是動手嘗試。複製下面討論的全部實現的類並且運行它。其中對於每一個實現幾乎都有一個小的測試。

package net.reversecoding.examples;
import static java.util.stream.Collectors.joining;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class CsvUtil {
private static final String SEPARATOR = ",";
public static String toCsv(List<String> listToConvert){
return String.join(SEPARATOR, listToConvert);
}
@Test
public void toCsv_csvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "Milan,London,New York,San Francisco";
assertEquals(expected, toCsv(cities));
}
public static String toCsvStream(List<String> listToConvert){
return listToConvert.stream()
.collect(joining(SEPARATOR));
}
@Test
public void toCsvStream_csvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "Milan,London,New York,San Francisco";
assertEquals(expected, toCsv(cities));
}
public static String toCsvJava7(List<String> listToConvert){
StringBuilder csvBuilder = new StringBuilder();
for(String s : listToConvert){
csvBuilder.append(s);
csvBuilder.append(SEPARATOR);
}
String csv = csvBuilder.toString();
//Remove last separator
if(csv.endsWith(SEPARATOR)){
csv = csv.substring(0, csv.length() - SEPARATOR.length());
}
return csv;
}
@Test
public void toCsvJava7_csvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "Milan,London,New York,San Francisco";
assertEquals(expected, toCsvJava7(cities));
}
public static String toUpperCaseCsv(List<String> listToConvert){
return listToConvert.stream()
.map(String::toUpperCase)
.collect(joining(SEPARATOR));
}
@Test
public void toUpperCaseCsv_upperCaseCsvFromListOfString(){
List<String> cities = Arrays.asList(
"Milan", "London", "New York", "San Francisco");
String expected = "MILAN,LONDON,NEW YORK,SAN FRANCISCO";
assertEquals(expected, toUpperCaseCsv(cities));
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章