在单独的行上使用 toString() 方法返回 Java 中的集合元素

Returning elements of a set in Java using toString() method on separate lines

我正在对 Java 中 Set<String> 的 return 个元素使用 toString() 方法,但每个元素都在单独的一行中。

代码示例:

import java.util.Set;

public class Animals{
    Set<String> animals;
    String newanimal;

    public Anmimals (Set<String> animals){
        this.animals = animals;
        }

    public setAnimals(String newanimal){
        this.newanimal = newanimal;
        animals.add(newanimal);
    }

    public String toString(){
        /* this is where my problem is i want to return the set (below), 
           however i also need each animal to be on a new line */
        return animal
    }

}

我能找到的唯一有用的东西,最后都建议不要使用 toString() 而是使用实际的 class 和 System.out.println() 来打印信息,但是,此特定问题需要 toString()

是否可以向该方法添加一个 for 循环并遍历每个方法,因为我 return 使用 \n 单独一行的每个元素?欢迎所有建议,因为这个,即使是可能的,似乎真的很乱。

我会流式传输集合,将每个元素转换为字符串并使用行分隔符连接它们:

@Override
public String toString() {
    return animals.stream()
                  .map(Object::toString)
                  .collect(Collectors.joining(System.lineSeparator()));
}

编辑:
编辑问题后,很明显问题是关于加入 Set<String>,而不是任何旧的 Set。在这种情况下,解决方案可以大大简化:

@Override
public String toString() {
    return String.join(System.lineSeparator(), animals);
}

你的代码有很多错误。

import java.util.HashSet;
import java.util.Set;

public class Animals{
    Set<String> animals;
    //String newanimal; delete this!

    //Constructor allows users to set animals using a set.
    public Animals (Set<String> animals){
        this.animals = animals;
        }

    //This default constructor is needed because you did not do Set<String> animals = new HashSet();
    public Animals()
    {
        this.animals = new HashSet();
    }

    //This method adds new elements to the animal set. What you did is wrong, so look over and compare
    public void setAnimals(String newanimal){
        animals.add(newanimal);
    }

    //The toString method you were asking about. I used StringBuilder but you can use someString += item + "\n".
    @Override
    public String toString(){
        /* this is where my problem is i want to return the set (below), 
           however i also need each animal to be on a new line */
        StringBuilder stringBuilder = new StringBuilder();
        for(String item : animals)
        {
            stringBuilder.append(item).append("\n");
        }

        return stringBuilder.toString();
    }
}