how to make single string of all key and values of map using lambda expression or stream - string

Map attributeMap = new TreeMap<>();
attributeMap.put("C","FIRSTNAMe");
attributeMap.put("C2","LASTNAMe");
attributeMap.put("C3","1111");
attributeMap.put("C4","ABCNAMe");
How to make single String of above example
output is c,c2,c3,c4 and FIRSTNAMe,LASTNAMe,'1111',ABCNAMe

Something like this:
Predicate<String> predicate = "1111"::equals;
String left = attributeMap.keySet().stream().map(String::toLowerCase).collect(Collectors.joining(","));
String right = attributeMap.values().stream().map(x -> (predicate.test(x) ? "'" + x + "'" : x)).collect(Collectors.joining(","));
System.out.println(left + right);

Related

how to extract an integer range from a string

I have a string that contains different ranges and I need to find their value
var str = "some text x = 1..14, y = 2..4 some text"
I used the substringBefore() and substringAfter() methodes to get the x and y but I can't find a way to get the values because the numbers could be one or two digits or even negative numbers.
One approach is to use a regex, e.g.:
val str = "some text x = 1..14, y = 2..4 some text"
val match = Regex("x = (-?\\d+[.][.]-?\\d+).* y = (-?\\d+[.][.]-?\\d+)")
.find(str)
if (match != null)
println("x=${match.groupValues[1]}, y=${match.groupValues[2]}")
// prints: x=1..14, y=2..4
\\d matches a single digit, so \\d+ matches one or more digits; -? matches an optional minus sign; [.] matches a dot; and (…) marks a group that you can then retrieve from the groupValues property. (groupValues[0] is the whole match, so the individual values start from index 1.)
You could easily add extra parens to pull out each number separately, instead of whole ranges.
(You may or may not find this as readable or maintainable as string-manipulation approaches…)
Is this solution fit for you?
val str = "some text x = 1..14, y = 2..4 some text"
val result = str.replace(",", "").split(" ")
var x = ""; var y = ""
for (i in 0..result.count()-1) {
if (result[i] == "x") {
x = result[i+2]
} else if (result[i] == "y") {
y = result[i+2]
}
}
println(x)
println(y)
Using KotlinSpirit library
val rangeParser = object : Grammar<IntRange>() {
private var first: Int = -1
private var last: Int = -1
override val result: IntRange
get() = first..last
override fun defineRule(): Rule<*> {
return int {
first = it
} + ".." + int {
last = it
}
}
}.toRule().compile()
val str = "some text x = 1..14, y = 2..4 some text"
val ranges = rangeParser.findAll(str)
https://github.com/tiksem/KotlinSpirit

how separate string into key/value pair in dart?

how can a string be separated into key/value pair in dart? The string is separated by a "=". And how can the pair value be extracted?
main(){
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
Map<String ,dynamic> map = {};
for (String s in stringTobeSeparated) {
var keyValue = s.split("=");
//failed to add to a map , to many positiona arguments error
map.addAll(keyValue[0],keyValue[1]);
}
}
The split() function gives you a List of Strings, so you just need to check if the length of this List is equal to 2 and then you can add those values in a Map like this:
Map<String, String> map = {};
for (String s in stringTobeSeparated) {
var list = s.split("=");
if(list.length == 2) {
// list[0] is your key and list[1] is your value
map[list[0]] = list[1];
}
}
You can use map for this, the accepted answer is correct, but since your string looks like this
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
I would rather use regex to remove spaces from final result (replace the line with split with this):
var list = s.split(RegExp(r"\s+=\s+"));

Grails convert String to Map with comma in string values

I want convert string to Map in grails. I already have a function of string to map conversion. Heres the code,
static def StringToMap(String reportValues){
Map result=[:]
result=reportValues.replace('[','').replace(']','').replace(' ','').split(',').inject([:]){map,token ->
List tokenizeStr=token.split(':');
tokenizeStr.size()>1?tokenizeStr?.with {map[it[0]?.toString()?.trim()]=it[1]?.toString()?.trim()}:tokenizeStr?.with {map[it[0]?.toString()?.trim()]=''}
map
}
return result
}
But, I have String with comma in the values, so the above function doesn't work for me. Heres my String
[program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]
my function returns ABC only. not ABC, INC. I googled about it but couldnt find any concrete help.
Generally speaking, if I have to convert a Stringified Map to a Map object I try to make use of Eval.me. Your example String though isn't quite right to do so, if you had the following it would "just work":
// Note I have added '' around the values.
​String a = "[program_type:'', subsidiary_code:'', groupName:'', termination_date:'', effective_date:'', subsidiary_name:'ABC']"
Map b = Eval.me(a)​
// returns b = [program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC]
If you have control of the String then if you can create it following this kind of pattern, it would be the easiest solution I suspect.
In case it is not possible to change the input parameter, this might be a not so clean and not so short option. It relies on the colon instead of comma values.
​String reportValues = "[program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]"
reportValues = reportValues[1..-2]
def m = reportValues.split(":")
def map = [:]
def length = m.size()
m.eachWithIndex { v, i ->
if(i != 0) {
List l = m[i].split(",")
if (i == length-1) {
map.put(m[i-1].split(",")[-1], l.join(","))
} else {
map.put(m[i-1].split(",")[-1], l[0..-2].join(","))
}
}
}
map.each {key, value -> println "key: " + key + " value: " + value}
BTW: Only use eval on trusted input, AFAIK it executes everything.
You could try messing around with this bit of code:
String tempString = "[program_type:11, 'aa':'bb', subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]"
List StringasList = tempString.tokenize('[],')
def finalMap=[:]
StringasList?.each { e->
def f = e?.split(':')
finalMap."${f[0]}"= f.size()>1 ? f[1] : null
}
println """-- tempString: ${tempString.getClass()} StringasList: ${StringasList.getClass()}
finalMap: ${finalMap.getClass()} \n Results\n finalMap ${finalMap}
"""
Above produces:
-- tempString: class java.lang.String StringasList: class java.util.ArrayList
finalMap: class java.util.LinkedHashMap
Results
finalMap [program_type:11, 'aa':'bb', subsidiary_code:null, groupName:null, termination_date:null, effective_date:null, subsidiary_name:ABC, INC:null]
It tokenizes the String then converts ArrayList by iterating through the list and passing each one again split against : into a map. It also has to check to ensure the size is greater than 1 otherwise it will break on f[1]

How to calculate average from multiple values in Spark

I have a mapper that emit key/value pairs(composite keys and composite values separated by comma).
e.g
key: a,b,c,d Value: 1,2,3,4,5
key: a1,b1,c1,d1 Value: 5,4,3,2,1
...
...
key: a,b,c,d Value: 5,4,3,2,1
I could easily SUM these values using reduceByKey.
e.g
reduceByKey(new Function2<String, String, String>() {
#Override
public String call(String value1, String value2) {
String oldValue[] = value1.toString().split(",");
String newValue[] = value2.toString().split(",");
int iFirst = Integer.parseInt(oldValue[0]) + Integer.parseInt(newValue[0]);
int iSecond = Integer.parseInt(oldValue[1]) + Integer.parseInt(newValue[1]);
int iThird = Integer.parseInt(oldValue[2]) + Integer.parseInt(newValue[2]);
int iFourth = Integer.parseInt(oldValue[3]) + Integer.parseInt(newValue[3]);
int iFifth = Integer.parseInt(oldValue[4]) + Integer.parseInt(newValue[4]);
return iFirst + "," + iSecond + ","
+ iThird+ "," + iFourth+ "," + iFifth;
}
});
But the problem is how do I find average of just one of these values. Lets assume I want to SUM iFirst, iSecond, iThird and iFourth but I want to find Average of iFifth. How do i do it? With a simple key/value pairs I could use mapValues function but not sure how I could do it with my example. Please advice.
I've used foldByKey function to resolve this issue.

How to sum up elements of an arraylist having type String?

I have an arraylist consisting of decimal numbers and i m supposed to take the average of last 4 elements of this arraylist.And these rational number are type of String.
private void average(String confidence) {
if(myList.size() >= 4) {
String t = myList.get(myList.size()-1);
String d = myList.get(myList.size()-2);
String f = myList.get(myList.size()-3);
String h = myList.get(myList.size()-4);
String s = (t + d + f+h) ;
long fin = Long.parseLong(s);
long result = fin/4 ;
System.out.println("Average is: "+result);
}
but this method does not work.Could you please tell me what kind of changes am i supposed to do or any advices of doing this? Thanks a lot in advance!!!
Your issue is the String s = (t + d + f+h) part. You're just appending 4 Strings right now.
You need to convert them first.
And your result will be wrong, you need to divide by 4, not 3.
Colleen's answer is good, so long as you remember to change the type to reflect what Long.parseLong() returns. I'd reply, but I'm too new.
if(myList.size() >= 4) {
Double t = Double.parseLong(myList.get(conf.size()-1));
Double d = Double.pareseLong(myList.get(conf.size()-2));
Double f = Double.parseLong(myList.get(conf.size()-3));
Double h = Double.parseLong(myList.get(conf.size()-4));
Double result = (t + d + f + h) / 3 ;
System.out.println("meanAsrConfidence is: "+result);
}
You need to convert before you add. + on Strings means concatenate.
if(myList.size() >= 4) {
//I'm guessing all of these conf.size() calls are meant to be myList.size()
double t = Double.parseDouble(myList.get(conf.size()-1));
double d = Double.pareseDouble(myList.get(conf.size()-2));
double f = Double.parseDouble(myList.get(conf.size()-3));
double h = Double.parseDoublemyList.get(conf.size()-4));
double s = (t + d + f+h) ;
double result = s/3 ; //should be 4
System.out.println("meanAsrConfidence is: "+result);
}
What you are doing now is, for example:
t=1, d=2, f=3, h=4
s = 1234
Also:
you need to divide by 4, not 3
what is conf? Why are you not calling myList.size()?
you're passing a String as an argument when you probably want to be passing myList

Resources