Say, I have a List students;
Person is defined like the following
class Person {
String id;
String name;
}
After getting the students, is the a qucik way to get a list of ids as used, in th开发者_如何学Ce form List ids.
Guava has Lists.transform function available. You pass in the list you want to transform and return elements associated to the list.
List<Person> people = ...;
List<String> ids = Lists.transform(people, new Function<People, String>(){
public String apply(People person){
return person.getId();
}
});
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Lists.html
If you are looking for something like a map
function as used in other languages, which build up a new list extracting just the IDs, then no, that's not directly feasible (unless by using some external collection API).
You should go the most straightforward way: iterating on the list and building up a new one by selecting just the IDs.
A way to get these things, like I mentioned, is for example to use a TransformIterator
together with a Transformer
but these are tools that doesn't come with SDK by default as they reside in Apache Collections (take a look here).
Just like Jack said, Or you can split the id's and make a new sequence out of that and iterate through that.
精彩评论