23 March 2010

Creating a set from its elements

Valid since: op4j 1.0

Description
Easily create a set containing some objects.

Scenario
Having some objects of type User called user1, user2 and user3, we want to create a Set<User> object containing them.

Recipe
Create a set operator on the objects and don't execute any action on it, just return the result:

Set<User> users = 
    Op.onSetFor(user1, user2, user3).get();

Comments
Sets created by op4j are always ordered sets (java.util.LinkedHashSet).

Compare this to the the non-op4j Java equivalent:

Set<User> users= new LinkedHashSet<User>();
users.add(user1);
users.add(user2);
users.add(user3);

No comments:

Post a Comment