【问题标题】:Convert String returning method to List<String> returning method in Java将 String 返回方法转换为 Java 中的 List<String> 返回方法
【发布时间】:2021-10-09 10:54:50
【问题描述】:

我希望以下方法返回 String 类型的 List 而不是 String 返回类型,调用后续“build”的另一个方法将接收 String 类型的 List(不是 StringBuilder)

public String build(String Uri, String Id) {

        StringBuilder DocUri = new StringBuilder();
        if (Uri.contains("newString")) {
            DocUri.append("user-profile1/users/").append(Id).append("/user.xml");
            DocUri.append("user-profile2/users/").append(Id).append("/user.xml");
            DocUri.append("user-profile3/users/").append(Id).append("/user.xml");
        }
 
        return DocUri.toString();
    }

输出应该是: 其中 '1' 是传递给上述方法的 ID

[user-profile1/users/1/user.xml, user-profile2/users/1/user.xml, user-profile3/users/1/user-profile.xml]

【问题讨论】:

    标签: java list arraylist


    【解决方案1】:

    你可以试试这样的,

    public List<String> build(String Uri, String Id) {
        List<String> values = new ArrayList<>();
        if (Uri.contains("newString")) {
            for (int i = 1; i <= 3; i++) {
                values.add(String.format("user-profile%s/users/%s/user.xml",i,Id));
            }
         }
        return values;
    }
    

    如果你想追加更多user-profile,你可以增加for-loop中的值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2016-11-06
      • 2017-08-25
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多