I'm working in a declarative pipeline, and I have a string that looks like this:
'[[key_A:value1, key_B:value2, key_C:value3],[key_A:value4, key_B:value5, key_C:value6],[key_A:value7, key_B:value8, key_C:value9]]'
Can I get help on what the quickest way is to turn the string into a map, then retrieve values of each map in the arraylist?
Can I get help on what the quickest way is to turn the string into a
map, then retrieve values of each map in the arraylist?
The input string you provide doesn't look like a map, it looks like a list of map. You can turn the string into a list of map using something like this (notice that the values here are quoted so they are strings, otherwise you would have to provide variables for value1, value2 etc):
def inputString = '[[key_A:"value1", key_B:"value2", key_C:"value3"],[key_A:"value4", key_B:"value5", key_C:"value6"],[key_A:"value7", key_B:"value8", key_C:"value9"]]'
def inputList = Eval.me (inputString)
Then you could iterate over that list to retrieve the maps and do whatever you want to do with the values in the maps:
def inputString = '[[key_A:"value1", key_B:"value2", key_C:"value3"],[key_A:"value4", key_B:"value5", key_C:"value6"],[key_A:"value7", key_B:"value8", key_C:"value9"]]'
def inputList = Eval.me (inputString)
inputList.each { Map m ->
println m.values()
}
Related
I want to get a list of String in ArrayList<Array<String>> by using stream() and map in Kotlin.
Each Array<String> of my arrayList has 3 values and I want to get the first index value and the last index value of each array.
This is my code:
fun main(args: Array<String>) {
val result: List<String>
val obj1 = arrayOf("fruit", "Mangue", "Africa")
val obj2 = arrayOf("Milk", "Soja", "Europ")
val obj3 = arrayOf("Meat", "cochon","Asia")
val myArrayList: ArrayList<Array<String>> = ArrayList<Array<String>>(3)
val myList: MutableList<Array<String>> = mutableListOf<Array<String>>()
myList.add(obj1)
myList.add(obj2)
myList.add(obj3)
myArrayList.addAll(myList)
result = myArrayList.stream().map{it -> ("${it[0]}-${it[2]}")}.toList()
println("ArrayList of objects :")
println(myArrayList)
println("my list of String result")
println(result)
}
I want to have this list of String in my result:
[fruit-africa,milk-Europ,Meat-Asia]
Also, when I print myArrayList, I have a bad result:
ArrayList of objects :
[[Ljava.lang.String;#5caf905d, [Ljava.lang.String;#27716f4, [Ljava.lang.String;#8efb846]
How can I do it, please?
Your Question
When I run your code, this is the output I see:
ArrayList of objects :
[[Ljava.lang.String;#5b480cf9, [Ljava.lang.String;#6f496d9f, [Ljava.lang.String;#723279cf]
my list of String result
[fruit-Africa, Milk-Europ, Meat-Asia]
And in your question, you have:
I want to have this list of String in my result:
[fruit-africa,milk-Europ,Meat-Asia]
So, it looks like you already have the output you want for result. The only difference from the actual output is the lack of a space after each comma. If you don't want that space, then use joinToString to customize the output:
println(result.joinToString(",", "[", "]"))
As for:
[[Ljava.lang.String;#5b480cf9, [Ljava.lang.String;#6f496d9f, [Ljava.lang.String;#723279cf]
You see that output because arrays don't override the toString() function, and therefore use the default implementation. In Kotlin, you can use contentToString() to get similar output as you see when printing a List.
println(myArrayList.joinToString(", ", "[", "]") { it.contentToString() })
So, here is the updated code with the above changes:
fun main(args: Array<String>) {
val result: List<String>
val obj1 = arrayOf("fruit", "Mangue", "Africa")
val obj2 = arrayOf("Milk", "Soja", "Europ")
val obj3 = arrayOf("Meat", "cochon","Asia")
val myArrayList: ArrayList<Array<String>> = ArrayList<Array<String>>(3)
val myList: MutableList<Array<String>> = mutableListOf<Array<String>>()
myList.add(obj1)
myList.add(obj2)
myList.add(obj3)
myArrayList.addAll(myList)
result = myArrayList.stream().map{it -> ("${it[0]}-${it[2]}")}.toList()
println("ArrayList of objects :")
println(myArrayList.joinToString(", ", "[", "]") { it.contentToString() })
println("my list of String result")
println(result.joinToString(",", "[", "]"))
}
Which gives this output:
ArrayList of objects :
[[fruit, Mangue, Africa], [Milk, Soja, Europ], [Meat, cochon, Asia]]
my list of String result
[fruit-Africa,Milk-Europ,Meat-Asia]
Potential Improvements
With all that said, there are a few things you can simplify in your code:
This is a minor point, but since you don't use the args parameter you can actually omit it.
Your myList is not necessary; you can add your arrays directly to myArrayList.
Given the small number of elements in each array, and the small number of arrays, you can actually create the List<Array<String>> and populate it with a single listOf.
For variable types, you should prefer using List, the interface, rather than ArrayList, the implementation. This is known as "programming to an interface". Preferring List also means better use of listOf and mutableListOf, which are the idiomatic ways of creating lists in Kotlin.
You should prefer using List over arrays. In other words, create a List<List<String>> instead of a List<Array<String>>.
Lists do override the toString() method, providing readable output. Also, lists have better API support and work better with generics.
You don't need to use stream(). Kotlin provides many extension functions for arrays and Iterables, one of those being map which returns a List. Yes, these transformation functions are eagerly evaluated, unlike with streams, but given you're only performing one transfomration this doesn't really matter (in fact, the stream is likely less performant).
See kotlin.collections for the available built-in extension functions.
Given you want the first and last elements of each array, I would use first() and last().
Here is the simplified code (I added explicit types to make it clearer what the variables reference):
fun main() {
val lists: List<List<String>> = listOf(
listOf("Fruit", "Mangue", "Africa"),
listOf("Milk", "Soja", "Europe"),
listOf("Meat", "Cochon", "Asia")
)
println("List of lists of strings:")
println(lists)
val result: List<String> = lists.map { "${it.first()}-${it.last()}" }
println("Result:")
println(result)
}
Output:
List of Arrays:
[[Fruit, Mangue, Africa], [Milk, Soja, Europe], [Meat, Cochon, Asia]]
Result:
[Fruit-Africa, Milk-Europe, Meat-Asia]
Let's say I have an array of strings and I want to get a list with objects that match, such as:
var locales=Locale.getAvailableLocales()
val filtered = locales.filter { l-> l.language=="en" }
except, instead of a single value I want to compare it with another list, like:
val lang = listOf("en", "fr", "es")
How do I do that? I'm looking for a one-liner solution without any loops. Thanks!
Like this
var locales = Locale.getAvailableLocales()
val filtered = locales.filter { l -> lang.contains(l.language)}
As pointed out in comments, you can skip naming the parameter to the lambda, and use it keyword to have either of the following:
val filtered1 = locales.filter{ lang.contains(it.language) }
val filtered2 = locales.filter{ it.language in lang }
Just remember to have a suitable data structure for the languages, so that the contains() method has low time complexity like a Set.
I'm trying to get a list of ID's from a JSON array in Groovy. I know how to get the ID's using the regular FOR loop, but I would like to know how to do the same with the each method. I'm not sure how to implement that. Does anyone have any idea?
Thank you in advance. Here's my code that works just fine using the regular for loop. However I would like to do it with the each method.
import groovy.json.*
def restresponse = '[{"id":5, "name":"Bob"},{"id":8, "name":"John"},{"id":12, "name":"Jim"},{"id":20, "name":"Sally"}]'
def json = new JsonSlurper().parseText(restresponse)
def myListOfIDs = []
for (int i = 0; i < json.size; i++) {
myListOfIDs.add(json[i].id) // getting all ID's for each SourceSystem
}
log.info(myListOfIDs) // This prints out all this IDs
The shortest way to perform this "conversion" is by using the Groovy's Collection collect method, e.g.:
def myListOfIDs = json.collect { ele -> ele.id }
EDIT: As pointed out by #dmahapatro there's an even shorter possibility:
def myListOfIDs = json*.id
I have an Array[String] in scala like this
my_array: Array[String] = Array(RED;BLUE, RED;PINK, RED;ORANGE, RED;WHITE, RED;YELLOW,
RED;GREY,GREEN;BLUE, GREEN;PINK, GREEN;BROWN, GREEN;ORANGE, GREEN;WHITE, GREEN;YELLOW, GREEN;GREY)
and I need to get this result
my_new_array: Array[Array[String]] = Array(Array(RED;BLUE, RED;PINK, RED;ORANGE, RED;WHITE,RED;YELLOW, RED;GREY),
Array(GREEN;BLUE, GREEN;PINK, GREEN;BROWN, GREEN;ORANGE, GREEN;WHITE, GREEN;YELLOW, GREEN;GREY),
Array(RED;BLUE, GREEN;BLUE), Array(RED;PINK, GREEN;PINK),
Array(RED;ORANGE, GREEN;ORANGE), Array(RED;WHITE, GREEN;WHITE),
Array(RED;YELLOW, GREEN;YELLOW), Array(RED;GREY, GREEN;GREY))
These should be te steps
get a list of unique colors. this means I have to split by ";" each string
once I have this list I have to create a new Array contained the original strings grouped by each single color
Does anyone have an hint?
Provided I've understood your question correctly, this should work (probably not the most efficient solution ever)
myArray
.flatMap(_.split(';')) // get all the colors
.distinct // get the unique set of colors
.map(color => myArray.filter(_.contains(color))) // map each color to each group containing it
I'm using contains assuming that for "YELLOW" you want to match both "YELLOW";"RED" and "RED";"YELLOW".
In case you want to match only the former, you can use startsWith intead.
I have an array loaded in, and been playing around in the REPL but can't seem to get this to work.
My array looks like this:
record_id|string|FALSE|1|
offer_id|decimal|FALSE|1|1,1
decision_id|decimal|FALSE|1|1,1
offer_type_cd|integer|FALSE|1|1,1
promo_id|decimal|FALSE|1|1,1
pymt_method_type_cd|decimal|FALSE|1|1,1
cs_result_id|decimal|FALSE|1|1,1
cs_result_usage_type_cd|decimal|FALSE|1|1,1
rate_index_type_cd|decimal|FALSE|1|1,1
sub_product_id|decimal|FALSE|1|1,1
campaign_id|decimal|FALSE|1|1,1
When I run my command:
for(i <- 0 until schema.length){
val convert = schema(i).toString;
convert.split('|').drop(2);
println(convert);
}
It won't drop anything. It also is not splitting it on the |
Strings are immutable, and so split and drop don't mutate the string - they return a new one.
You need to capture the result in a new val
val split = convert.split('|').drop(2);
println(split.mkString(" "));
Consider also defining a lambda function for mapping each item in the array, where intermediate results are passed on with the function,
val res = schema.map(s => s.toString.split('|').drop(2))