2 回答
TA贡献1816条经验 获得超6个赞
解决方案:
假设您在 MyCustom 类中有一个 String 变量,例如:
public class MyCustom {
private String strName;
public MyCustom(String name) {
this.strName = name;
}
public void setName(String name) {
this.strName = name;
}
public String getName() {
return this.strName;
}
}
然后,您可以执行以下操作:
for (MyCustom value : fullList) {
customFullList.add(new MyCustom(value))
}
希望能帮助到你。
TA贡献1784条经验 获得超9个赞
首先,没有必要让该username字段成为类的公共成员MyCustom。由于您通过 getter/setter 公开访问该字段是错误的。
除此之外,您可以轻松使用流和映射函数MyCustom从字符串流创建新实例。
为了避免样板代码,我会继续创建一个静态创建者方法,MyCustom如下所示:
public class MyCustom {
private String userName;
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
public static MyCustom from(final String userName) {
MyCustom custom = new MyCustom();
custom.setUserName(userName);
return custom;
}
}
然后我将使用它作为方法引用将字符串转换为 MyCustoms,从而将它们收集到一个新列表中,如下所示:
List<String> list = new ArrayList<>();
List<MyCustom> customs = list.stream()
.map(MyCustom::from)
.collect(Collectors.toList());
最后,还要避免使用具体类型初始化列表(例如ArrayList<String> someList = new ArrayList<>;'。对接口进行编码要好得多,因此执行类似List<String> someList = new ArrayList<>.
添加回答
举报