Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The fully "functional" way, using Guava, would combine <code>Ordering#explicit()</code> with <code>Ordering#onResultOf()</code></p> <pre><code>public class UserService { @Inject private UserDao userDao; public List&lt;User&gt; getUsersWithIds(List&lt;Integer&gt; userIds) { List&lt;User&gt; users = userDao.loadUsersWithIds(userIds); Ordering&lt;User&gt; orderById = Ordering.explicit(userIds).onResultOf(UserFunctions.getId()); return orderById.immutableSortedCopy(users); } } </code></pre> <p>You could declare an anonymous function inline, but I like to declare my functions as static factory methods in a separate class, for a cleaner code (the verbosity of Java's function declarations is hidden in the utility class):</p> <pre><code>/** * Static factory methods to create {@link Function}s for {@link User}s. */ public final class UserFunctions { private UserFunctions() { /* prevents instantiation */ } /** * @return a {@link Function} that returns an {@link User}'s id. */ public static Function&lt;User, Integer&gt; getId() { return GetIdFunction.INSTANCE; } // enum singleton pattern private enum GetIdFunction implements Function&lt;User, Integer&gt; { INSTANCE; public Integer apply(User user) { return user.getId(); } } } </code></pre> <hr> <p>As mentioned by @Arne in a comment, this can be simplified in Java 8, using a method reference instead of the <code>UserFunctions</code> class:</p> <pre><code>public class UserService { @Inject private UserDao userDao; public List&lt;User&gt; getUsersWithIds(List&lt;Integer&gt; userIds) { List&lt;User&gt; users = userDao.loadUsersWithIds(userIds); Ordering&lt;User&gt; orderById = Ordering.explicit(userIds).onResultOf(User::getId); return orderById.immutableSortedCopy(immutableSortedCopy(users)); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload