java - 如何使用 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);
}
在 ? 中查找值的简单方法。
解决方案
我不确定我是否理解你的问题。下次您在 StackOverflow 上提出问题时,请尝试提供您正在使用的类,并尝试解释您想要实现的目标。
话虽如此,要使用流将一个对象转换为另一个对象,您可以使用map()。像这样的东西:
List<AnotherType> anotherType = types
.stream()
.map(t -> new AnotherType(t.getTypeValue1(), t.getTypeValue2()))
.collectors(Collectors.toList());
推荐阅读
- google-cloud-platform - 使用 bq CLI 在 bigquery 中列出数据集中的所有表并将它们存储到谷歌云存储
- c++ - clang:候选模板被忽略:替换失败:typedef'type'不能用类说明符引用
- rabbitmq - Ansible 没有使用 rabbitmq_user 模块创建 RabbitMQ 用户
- java - 如何将对象中的多个字段与对象队列进行比较?
- javascript - 将 var 声明(例如 var x;)覆盖以前的值
- java - 如何从 Java Play 框架中的动作返回结果?
- google-drive-api - 如何从谷歌绘图中提取文本?
- vue.js - 我不能在 Vue.js 中使用计算的 GroupBy 数组
- mysql - 我无法查看我刚刚创建的表格?我不知道为什么
- r - 删除列中的部分字符串