Dasma Dasma - 6 months ago 41
Groovy Question

How can i filter a List neighbors is equal? Request something like unique()

If have list of af string, how can filter so equal neighbors only appears one?

Example:

['0.1', '0.1', '0.2','0.3','0.3','0.1','0.2']


should result in

['0.1', '0.2','0.3','0.1','0.2']


notice that element 0, 1 only appears once and element 4 and 5 also appears only once.

If use unique:

['0.1', '0.1', '0.2','0.3','0.3','0.1','0.2'].unique()


the result will be:

['0.1', '0.2','0.3'] //what is not wanted


Any suggestions for the best groovy method?

fsi fsi
Answer Source

So if you want remove duplicated neighbors, you should get next item from current loop. i come up something like this:

def example =  ['0.1', '0.1', '0.2','0.3','0.3','0.1','0.2']
def array = []
example.eachWithIndex { item, index ->
    def next = index  < example.size() - 1 ? example[ index  + 1 ] : null
    if(next != item) {
        array.push(item)
    }
}

println array ‚Äč
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download