Joseph Wilson
Joseph Wilson

Reputation: 1

How to sort alphanumeric list based on priority in groovy?

Below are 3 static lists

a_list = ["z1", "a2", "x4", "n7", "v10"]
b_list = ["l3","b10", "b1", "f5", "y23"]
c_list = ["l2", "c12", "d15", "n17", "c1"]

At any given payload I would get the below inputs with different input lists and priorities. Based on the priority, the output list has to be sorted to be on top

Input_list = ["f5", "y23","z1", "a2","l2", "c12"]
Priority = "c"

Expected Result:

Output_list = ["l2", "c12", "f5", "y23","z1", "a2"]

If the priority changes, then the sort order changes. How do I get this done in groovy?

Upvotes: 0

Views: 214

Answers (2)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

The order can be random, but if priority value is c all the items in c list should be on top

inputList = ["b10", "b1", "a1", "a2","c2", "c12"]
priority = "c"

inputList.sort {
  it.startsWith(priority) ? -1 : 1
}

// inputList will be [c2, c12, b10, b1, a1, a2]

Upvotes: 0

cfrick
cfrick

Reputation: 37033

First of all, I'd structure the config a little different. Keep the known priorities in a map, where the priority is the key and all the values for that priority are in a set.

Then you can sort the payload by checking, if the payload item is in the priority set (note that using just true/false to sort here might read little odd, so feel free to switch over to returning -1/1 or something easier to grasp):

def priorties = [
    a: ["z1", "a2", "x4", "n7", "v10"].toSet(),
    b: ["l3","b10", "b1", "f5", "y23"].toSet(),
    c: ["l2", "c12", "d15", "n17", "c1"].toSet(),
]
def payload = ["f5", "y23","z1", "a2","l2", "c12"]
def priority = "c"

assert priorties.containsKey(priority)
assert payload.sort{ ! priorties[priority].contains(it) } == ["l2", "c12", "f5", "y23","z1", "a2",]

Upvotes: 1

Related Questions