如何打印括号内的字符串列表?

How to print list of string inside bracket?

我是 Java 的新手。我在打印括号内用逗号分隔的字符串列表时遇到问题。

public class House extends Property { 
protected static List<String> paints;
public String paint;

public House() {
    super("House", 45);
    String paints = new String();
    System.out.print(paints);
}

public void addPaint(String paint) {
    this.paint = paint;
    ArrayList<String> House = new ArrayList<String>();
    House.add(" ");

public void display() {
    super.display();
    List<String> words = Arrays.asList(paint);
    StringJoiner strJoin = new StringJoiner(", ", " { ", " }");
    words.forEach((s)->strJoin.add(s));
    if (paint == null || "".equals(paint)) {
        System.out.print(" { }");
    }

    else {
    System.out.print(strJoin);
    }

public static void main(String[] args) {
        House house1 = new House();
        house1.addPaint("Red");
        house1.addPaint("Blue");
        house1.addPaint("Yellow");
        house1.display();
    }

有颜色的房子应该这样打印:

45 House { Red, Blue, Yellow }

或者像这样的没有颜色的房子(空):

45 House { }

但是,我的代码的输出只打印最后添加的颜色:

45 House { Yellow }

请帮帮我。谢谢

要使用前缀和后缀对字符串列表进行分组,您可以使用 Collectors.joining(CharSequence delimiter, CharSequence prefix,CharSequence suffix)),例如:

import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<String> colors = List.of("Red", "Blue", "Yellow");
        String result = colors.stream().collect(Collectors.joining(" , ", "{", "}"));
        System.out.println(result);
    }
}

这将打印 {Red , Blue , Yellow},如果列表为空,它将打印 {}

注意:

  • 我认为你应该检查你的模型设计^^ !
  • 我在我的示例中使用 List.of() 来演示“操作方法”,知道它需要 java 9 或更高版本
public class House {
    List<String> colors = new ArrayList<String>(); 
    public void addPaint(String color)
    {
        colors.add(color);        
    }
    public void display()
    {   String value = "";
        for (String color : colors)
        value += color + ", ";
        value = value.substring(0, value.length()-2);
        System.out.println("{ " + value + " }");
    }
}

public static void main(String[] args) {
    House house1 = new House();
    house1.addPaint("Red");
    house1.addPaint("Blue");
    house1.addPaint("Yellow");
    house1.display();
}

// Output: { Red, Blue, Yellow }

您已在此处将 paint 声明为字符串(而不是字符串列表)。

public String paint;

然后将字符串变量转换为列表。

List<String> words = Arrays.asList(paint);

这就是为什么列表 words 只有一个最后用 house1.addPaint() 添加的字符串,它只分配其中的字符串 this.paint = paint;

您可以通过多种方式修复它。但我会告诉需要最少更改的那个。

我的建议:

public void addPaint(String paint) {
    paints.add(paint);
}

List<String> words = Arrays.asList(paints);