[英]Is there a Java data structure that returns a set of a specific attribute in a collection of objects?
I have a collection of objects which are all the same object type. 我有一组对象,它们都是相同的对象类型。 Within that type there is an attribute that I want to access - in this case it's to add it to a comma separated list: 在该类型中,有一个我想要访问的属性 - 在这种情况下,它是将它添加到以逗号分隔的列表中:
String sep = ", ";
List<Item> items = db.findItems();
for (Item item : items)
{
result.append(item.getDescription() + sep);
} //for
return result.substring(0, results.length - sep.length());
It would be nice if I could just directly access that attribute from all the objects in the collections so that I could call Google Guava's Joiner function: 如果我可以直接从集合中的所有对象访问该属性,那么我可以调用Google Guava的Joiner函数:
return Joiner.on(", ").join(/*Description attribute collection here*/);
The kind of structure I'm thinking of is like a 2D array where each column represents an attribute and each row represents an object and so I want to be able to call either a specific row which returns the object or a specific column (attribute) that returns a collection of the attributes from all objects. 我想到的结构类似于2D数组,其中每列代表一个属性,每行代表一个对象,所以我希望能够调用返回对象的特定行或特定列(属性)返回所有对象的属性集合。
Does Java or a good third party have a data structure like this or would I need to create my own? Java或一个好的第三方是否有这样的数据结构,还是我需要创建自己的数据结构?
Cheers, 干杯,
Alexei Blue. 阿列克谢蓝。
Why don't you use Google's Guava to the fullest then? 你为什么不最充分地使用谷歌的番石榴呢?
Joiner.on(",").join(Collections2.transform(items, new Function<Item, String>() {
public String apply(Item input) {
return item.getDescription();
}
}));
You can write an inner Iterable
subclass that reaches into each object in a collection and emits the correct attribute. 您可以编写一个内部Iterable
子类,它可以到达集合中的每个对象并发出正确的属性。 See @Hiery's response, he got to the code faster... 看到@Hiery的回复,他更快地得到了代码......
Comming soon in JDK 8 with lambda expressions and method references 很快就在JDK 8中使用lambda表达式和方法引用
List<Jedi> jedis = asList(new Jedi("Obiwan",80), new Jedi("Luke", 35));
List<String> jediNames = jedis.map(Jedi::getName).into(new ArrayList<>()); //with metdod ref
Iterable<Integer> jediAges = jedis.map(j -> j.getAge()); //with lambdas
Depending on what you're doing you may even use the JDK 8 preview provided in the link. 根据您正在做的事情,您甚至可以使用链接中提供的JDK 8预览。
Alternatively, the library Lambdaj offers a way to do that. 或者, Lambdaj库提供了一种方法。
Silly, but I would opt for Item.toString(). 傻,但我会选择Item.toString()。 Doesn't there exist a map so you can do join(map)? 是否存在地图以便您可以加入(地图)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.