首页 > 解决方案 > 如何使用 Stream API 从对象列表中获取对象的值

问题描述

从下面的代码需要从列表中获取基于类型的值,

List<Type> types= Arrays.asList(new Type("type1","Values1"),new Type("type2","Values2"));

List<AnotherType> anotherTypes = new ArrayList<>();

for (Type type:types){
    AnotherType  anotherType = new AnotherType();
    
    anotherType.settype1Value(?);
    anotherType.settype2Value(?);

    anotherTypes.add(anotherType);
}

在 ? 中查找值的简单方法。

标签: javalambdajava-8java-stream

解决方案


我不确定我是否理解你的问题。下次您在 StackOverflow 上提出问题时,请尝试提供您正在使用的类,并尝试解释想要实现的目标。

话虽如此,要使用流将一个对象转换为另一个对象,您可以使用map()。像这样的东西:

List<AnotherType> anotherType = types
    .stream()
    .map(t -> new AnotherType(t.getTypeValue1(), t.getTypeValue2()))
    .collectors(Collectors.toList());

推荐阅读