Duracel
Duracel

Reputation: 134

Get collection of object.getSomething() from this object collection

Let's say I have a Collection<MyObject> and I want to get a new collection of something like Collection<Integer> with myObjects.getIntValues(). Can I make this fast and clear instead of making new Collection and iterate through all the collection members and add MyObject.getIntValue() to the new collection?

List<Int> list = new ArrayList<Int>;
for(MyObject obj : myCollection) {
    list.add(obj.getIntValue());
}

Upvotes: 0

Views: 203

Answers (2)

Philipp Murry
Philipp Murry

Reputation: 1682

You can use the copy Method of the Collection class if you just want a new collection of the same values as in the original one.

If you want to create a new collection with different values than in your original collection though (MyObject.getIntValue()), then I don't see a workaround for iterating through all your objects and programatically put the value into your new collection.

Be careful with the first variant though, as it only creates a shallow copy (the objects will be the same, only the references will be copied).

Upvotes: 0

Smutje
Smutje

Reputation: 18173

Example with Java 8 streams:

final List<Object> objects = Arrays.asList(1, 2, 3, 4);
final List<Integer> integers = objects.stream()
        .map(o -> (Integer) o)
        .collect(Collectors.toList());

Upvotes: 1

Related Questions