Java:将classA的集合转换为classB的集合
给定 Foo myFoos 列表,我需要将它们映射到不同类(例如 Bar)的集合。我现在这样做:
List<Bar> myBars = new...
for(Foo f : foos) {
Bar b = new Bar();
b.setAProperty(f.getProperty);
b.setAnotherProp(f.getAnotherProp);
myBars.add(b);
}
那么,有没有更简单的方法来做到这一点?当然这很简单,但我想知道是否有任何魔法可以将 foos 变成 bar 而无需手动遍历列表,特别是因为我的输入列表可能很大。
如果没有,你们知道编译器是否做了任何优化吗?我主要担心的是性能。
谢谢!
--
拉帕尔
Given a List of Foo myFoos, I need to map those to a collection of a different class, say Bar. I do it like this now:
List<Bar> myBars = new...
for(Foo f : foos) {
Bar b = new Bar();
b.setAProperty(f.getProperty);
b.setAnotherProp(f.getAnotherProp);
myBars.add(b);
}
So, is there an easier way to do this? Granted this is pretty easy, but I'm wondering if there's any magic out there that would morph the foos to bars without having to manually walk the list, particularly because my input list can be big.
If not, do you guys know if the compiler does anything to optimize this? I'm worried mainly about performance.
Thanks!
--
Llappall
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法真正避免遍历列表,因为您必须转换每个项目!
但是,如果您编写一个采用
Foo
的Bar
构造函数,则可以简化语法。然后你的循环可以变成:根据你的场景,另一种选择是根本不创建
Bar
列表。相反,您可以简单地添加Foo.getAsBar()
方法,以便根据需要动态生成Bar
对象。如果容器中的元素数量高于您需要访问它们的总次数,那么这可能会更有效。You can't really avoid walking the list, because you have to convert every item!
But you can simplify your syntax if you write a
Bar
constructor that takes aFoo
. Then your loop can become:Depending on your scenario, an alternative is to not create the list of
Bar
s at all. Instead, you can simply add aFoo.getAsBar()
method, so that you dynamically generate aBar
object as required. If the number of elements in the container is higher than the total number of times that you'll need to access them, then this may be more efficient.一个想法不是通用的解决方案,但在某些情况下可能是合适的:
拉取属性
每当实例化 Bar 时,不必将属性从 Foo 推送到 Bar,只需将 Foo 关联到新的 Bar并映射属性 getter 中的属性。
<代码>
这不会阻止您循环 Foos 来实例化 Bars。但它延迟了映射属性的工作。
One idea which is not a general solution, but could be appropriate in some situations:
Pull the properties
Instead of pushing the properties from Foo to Bar whenever a Bar is instantiated, just associate a Foo to a new Bar and map the properties in the property getters.
This does not prevent you from looping over Foos to instantiate Bars. But it delays the effort to map properties.
另一个想法,当然,只适用于极少数情况。
实现(某种)Fyweight 模式
先决条件:属性集
Foo
和Bar
是一样的。Foo
和Bar
的公共属性放入外部类中,例如Properties
。Properties
类型的属性。Bar
的新实例并希望从Foo
初始化它时,只需将 Properties 从Foo
实例传递给新的>Bar
实例。优点:
缺点:
Another idea, which is - granted - approriate in very rare cases only.
Implement (kind of) a Fyweight pattern
Prerequisite: The set of properties of
Foo
andBar
is the same.Foo
andBar
into an external class, sayProperties
.Properties
for Foo and Bar.Bar
and want to initialize it fromFoo
, just pass the Properties from theFoo
instance to the newBar
instance.Pros:
Cons: