Question

I want to select the top 3 items of a java List.

I know how to sort the List (please see the code), but I don't know how to select the top 3 entries of this list having the highest values ([3.0, 5.5, 7.2]).

I guess I could use subList(), but I want to know if there is a way to do this in lambdaj.

import java.util.Arrays;
import java.util.List;
import static ch.lambdaj.Lambda.*;

public class Example {
    public static void main(String[] args)
    {
        List<Double> list = Arrays.asList(5.5,1.5,7.2,3.0,0.5);
        System.out.println(list);
        List<Double> sortedList = sort(list,on(Double.class).doubleValue());
        System.out.println(sortedList);
    }
}
Was it helpful?

Solution

Why use lambdaj? This is a simple enough task that can be done like this:

List<Double> list = Arrays.asList(5.5,1.5,7.2,3.0,0.5);
System.out.println(list);

List<Double> sortedList = sort(list, on(Double.class).doubleValue());
System.out.println(Arrays.toString(sortedList.subList(0, 2).toArray()));

lambdaj has no real use here. Since you are only asking to get parts of the list, and not to modify it in any way, using Lists built in method is the best solution.

If you really want to use lambdaj, LambdaList has a subList() method, but that is exactly the same as the one in Java SE's List interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top