【问题标题】:How to get Value of object from list of objects by Using Stream API如何使用 Stream API 从对象列表中获取对象的值
【发布时间】:2020-07-14 12:24:42
【问题描述】:

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

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);
}

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

【问题讨论】:

  • types.stream().map(t-&gt;new AnotherType(...)).collect(toList());
  • 尝试再次清除您的问题并添加示例输入输出。
  • 你的意思是像anotherType.settype1Value(type.getType());吗?预期的结果是什么?另外,我们可以假设您的课程有通常的 getter 和 setter 吗?对不起,我不清楚这个问题,请编辑和澄清。

标签: java lambda java-8 java-stream


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2022-08-16
    • 2020-11-21
    • 1970-01-01
    • 2017-09-26
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多