有什么好的办法将集合list1改成集合list2这样的吗?详细看图

img


枚举类

img

集合list2

img


有什么好的写法吗?stream流可以实现吗?

List<Assert2> list2 = list1.stream().map(item -> {
            Assert2 assert2 = new Assert2();
            assert2.setId(item.getId());
            assert2.setSerialNum(item.getSerialNum());
            for (Enum e : Enum.values()) {
                if (e.getCode().equals(item.getType())) {
                    assert2.setTypeName(e.getMessage());
                    break;
                }
            }
            return assert2;
        }).collect(Collectors.toList());

你这个集合1对象中type是数值类型 集合2typeName是字符串。一般就循环判断赋值

类似这样,把那个转换方法换成枚举即可

    public static void main(String[] args) {
        List<Asset> list = Arrays.asList(new Asset(1001, 1, 1),
                new Asset(1001, 1, 2),
                new Asset(1001, 1, 3));
        List<Asset2> list2 = list.stream()
                .map(x -> new Asset2(x.getId(), x.getSerialNum(), type2Str(x.getType())))
                .collect(Collectors.toList());
        System.out.println(list2);
    }

    public static String type2Str(int type) {
        if (type == 1) return "入库";
        if (type == 2) return "归还";
        if (type == 3) return "出库";
        return null;
    }