How to get the top-x elements of a list

0
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: https://modelshare.mendix.com/models/cac33f27-6342-41fb-96ea-b1c40fd62529/get-topx-from-list Is there a better way? NB. the list is not in the database.
asked
4 answers
3

Tim,

Maybe this recently added appstore module can help:  https://appstore.home.mendix.com/link/app/81827/Enexis/ListUtils

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.

Mike

answered
3

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)
    {
        super(context);
        this.Param_List = Param_List;
        this.Param_needN = Param_needN;
    }

    @Override
    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) {
                new_List.add(Param_List.get(b));
            }    
        }
        return new_List;
        // END USER CODE
    }
...

answered
2

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.

answered
2

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.

See: https://modelshare.mendix.com/models/0279bdc4-8978-4f78-b647-7a2fc197c75b/get-topx-from-list-edit

answered