How to get the top-x elements of a list

The only way I can imagine to get the top-x elements out of a list of elements that is in memory, is by looping over the list. See my microflow: Is there a better way? NB. the list is not in the database.
4 answers


Maybe this recently added appstore module can help:

From the documentation for that module:

Example 2: Top-n query

To retrieve the top-10 records of a list, use the Filter function with the following transform function:

<xsl:for-each select="record"><xsl:if test="position() &lt;= 10'"><xsl:copy-of select="."/></xsl:if></xsl:for-each>

I would be curious to know if that works for you.



You can add this java action (code below) that takes 2 inputs : a list of Type parameter 'TypeParameter_1' and a Long.

The output is also a list of Type parameter 'TypeParameter_1'.

Java action is:

package somepkg.actions;

import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import com.mendix.systemwideinterfaces.core.IMendixObject;

public class Java_action_GetTopNFromList extends CustomJavaAction<java.util.List<IMendixObject>>
    private java.util.List<IMendixObject> Param_List;
    private java.lang.Long Param_needN;

    public Java_action_GetTopNFromList(IContext context, java.util.List<IMendixObject> Param_List, java.lang.Long Param_needN)
        this.Param_List = Param_List;
        this.Param_needN = Param_needN;

    public java.util.List<IMendixObject> executeAction() throws Exception
        // BEGIN USER CODE
        // throw new com.mendix.systemwideinterfaces.MendixRuntimeException("Java action was not implemented");
        int c = 0;
        java.util.List<IMendixObject> new_List = new java.util.ArrayList(); // creating list
        for (int b = 0; b < Param_List.size(); b++) {
            if (b < Param_needN) {
        return new_List;
        // END USER CODE


Hi Tim,

  After digging through the list actions, I can't find a way to do this without the loop you suggest or a loop of 'heads' or 'tails.'  You could implement a custom java action that uses the .SubList java utility.  That might be a nice addition to the communitycommons module.


I agree with Rob.

When Nr of objects not to use is smaller then the Nr of objects to use, then the following setup of the microflow will improve your microflow a bit. Only remove objects if needed and if needed only loop to remove.