Java:将一种元素类型的列表转换为另一种类型的列表 [英] Java: Converting lists of one element type to a list of another type
本文介绍了Java:将一种元素类型的列表转换为另一种类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个适配器框架,在该框架中,我需要将对象列表从一个类转换为另一个类.我可以像在
I'm writing an adapter framework where I need to convert a list of objects from one class to another. I can iterate through the source list to do this as in
Java:转换List< Integer>的最佳方法;列出< String>
但是,我想知道是否有一种方法可以在迭代目标列表时立即执行此操作,因此我不必遍历列表两次.
However, I'm wondering if there is a way to do this on the fly when the target list is being iterated, so I don't have to iterate through the list twice.
推荐答案
Java 8方法:
List<String> original = ...;
List<Wrapper> converted = original.stream().map(Wrapper::new).collect(Collectors.toList());
假定Wrapper
类具有接受String
的构造函数.
assuming Wrapper
class has a constructor accepting a String
.
这篇关于Java:将一种元素类型的列表转换为另一种类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文