[Java]リスト(List)をカンマ区切りで結合した文字列に変換するには?

Java

どうも、ちょげ(@chogetarou)です。

リスト(List)をカンマ区切りで結合した文字列に変換する方法を紹介します。

スポンサーリンク

方法

リスト(List)をカンマ区切りで結合した文字列に変換する方法は、2つあります。

String.join()

ひとつは、String.join()を使う方法です。

まず、Stringからjoin()を呼び出します。

そして、join()の第1引数にカンマの文字列、第2引数にリスト(List)を指定します。・

//list=対象のリスト
String result = String.join(",", list);

上記のString.join()は、第2引数のリスト(List)の要素をカンマ区切りで結合した文字列を生成します。

使用例

import java.util.ArrayList;

    
public class Main {

    public static void main(String[] args) throws Exception {
        ArrayList<String> nums = new ArrayList<String>(5);
        nums.add("one");
        nums.add("two");
        nums.add("three");
        nums.add("four");
        nums.add("five");
        
        String result = String.join(",", nums);
        
        System.out.println(result);
    }
}
出力:
one,two,three,four,five

Collectors.joining()

もうひとつは、Collectors.joining()を使う方法です。

まず、Collectorsをインポートします。

import java.util.stream.Collectors;

次に、リストからstream()、stream()からcollect()を呼び出します。

collect()の引数でリストからCollctors.joining()を呼び出します。

そして、joining()の引数にカンマの文字列を指定します。

//list=対象のリスト
String result = list.stream().collect(Collectors.joining(","));

上記のcollect()は、リスト(List)の要素をカンマ区切りで結合した文字列を生成します。

使用例

import java.util.ArrayList;
import java.util.stream.Collectors;
    
public class Main {

    public static void main(String[] args) throws Exception {
        ArrayList<String> nums = new ArrayList<String>(5);
        nums.add("one");
        nums.add("two");
        nums.add("three");
        nums.add("four");
        nums.add("five");
        
        String result = nums.stream().collect(Collectors.joining(","));
        
        System.out.println(result);
    }
}
出力:
one,two,three,four,five

まとめ

リスト(List)をカンマ区切りで結合した文字列に変換する方法は、次の2つです。

  • String.join()を使う方法
    String result = String.join(",", list);
  • Collectors.joining()を使う方法
    String result = list.stream().collect(Collectors.joining(","));

コメント

タイトルとURLをコピーしました