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

问题描述

我是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或更高版本
,

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

public String paint;

然后将String变量转换为List。

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

这就是为什么列表words仅包含最后一个与house1.addPaint()添加在一起的单个String的原因,而后者只是在其中分配了字符串this.paint = paint;

有很多方法可以修复它。但是,我将告诉您需要最少更改的对象。

我的建议:

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

List<String> words = Arrays.asList(paints);
,
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,Yellow }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...