Total Pageviews

2016/10/09

[Java 8] Convert a List of String to a Comma-Separated String

If I have a List of String looks like:
1
2
3
private List<String> getDummyPlayers() {
    return Arrays.asList("王 柏 融", "林 智 勝", "林 泓 育", "蔣 智 賢", "高 國 慶");
}

If I would like to convert it to String, and each player should separate with comma, i.e. 王 柏 融, 林 智 勝, 林 泓 育, 蔣 智 賢, 高 國 慶

Before Java 8, we may do this way:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
private String separatePlayersWithComma(){
    List<String> players =getDummyPlayers();
    String playersWithComma = "";
    for (int i = 0; i < players.size(); i++) {
        if (i == players.size() - 1) {
            playersWithComma = playersWithComma + players.get(i);
        } else {
            playersWithComma = playersWithComma + players.get(i) +", "; 
        }
    }
    return playersWithComma;
}


In Java 8, it is very easy and straightforward:
1
2
3
4
5
private String separatePlayersWithComma_usingJDK8(){
    List<String> players =getDummyPlayers();
    String playersWithComma = players.stream().collect(Collectors.joining(", "));
    return playersWithComma;
}






No comments: