【发布时间】:2021-02-26 05:54:37
【问题描述】:
我需要根据某些属性将一个列表拆分为多个列表。
List<Custom1> nums = new ArrayList<>();
List<Custom2> cats = new ArrayList<>();
List<Custom3> forms = new ArrayList<>();
list.stream().forEach(custom -> {
if (custom.getType().equalsIgnoreCase("N")) {
Custom1 attr = new Custom1();
attr.setAttrCd(custom.getCode());
attr.setValue(Float.parseFloat(custom.getValue()));
nums.add(attr);
} else if (custom.getType().equalsIgnoreCase("C")) {
Custom2 attr = new Custom2();
attr.setAttrCd(custom.getCode());
attr.setValue(Integer.parseInt(custom.getValue()));
cats.add(attr);
} else if (custom.getType().equalsIgnoreCase("F")) {
Custom3 attr = new Custom3();
attr.setAttrCd(custom.getCode());
attr.setValue(custom.getValue());
forms.add(attr);
}
});
使用流过滤器可以使相同的代码更好。
list.stream().filter(...).collect(toList())
但在我的情况下我需要迭代 3 次。 还有其他更好的方法吗?
【问题讨论】:
标签: java-8