Groovy - Select position for related arrays and verify contents
Hello,
I have been looking for almost a week now around how to best approach this but cannot find anything.
I have two arrays which are related that are storing values from a loop through a JDBC output
These arrays are set like this (i increments in loop, medium also contains common values within the array which is where type comes in to identify for what I want to use it for) Both arrays are the same size.
medium[i] = holder.getNodeValue(nodeStringMedium).toString()
type[i] = holder.getNodeValue(nodeStringType).toString()
Once I have them all stored I then want to search for where a value is within the medium which I was using:
log.info medium.findIndexValues {
it == "Post"
}
But due to that coming with multiple positions of post (1,4,6) it doesn't allow me to find the position in type using that.
I am looking for:
store as a variable the position where medium = X and type = Y
for example in the below I want to find the position of medium = "Post" and Type = "Alternative" which would be 4
Position | Medium | Type |
1 | Post | Standard |
2 | Alternative | |
3 | SMS | Standard |
4 | Post | Alternative |
5 | Mobile | Standard |
6 | Post | BackUp |
I'd go with a matrix-approach. Define three lists in a list, one for index and two for your values. The just run find on the index-column and use the value to test the other two columns for what you are looking for.
def matrix = [[],[],[]]; //Populate the matrix for this example 3.times { i -> matrix[0][i] = i matrix[1][i] = "POST $i" matrix[2][i] = "TYPE $i" } //matrix //[[1, 2, 3], //[POST 0, POST 1, POST 2], //[TYPE 0, TYPE 1, TYPE 2]] //Search the indices and check the other two columns //for their values using the current index int indexOfPost2Type2 = matrix[0].find { i -> matrix[1][i] == 'POST 2' && matrix[2][i] == 'TYPE 2' } //indexOfPost2Type2 == 2
try it out and see how that works. :)