To understand the map function in Streams better I was trying something like this:
String inputString="1+3+5";
Stream.of(inputString.split("\\+")).map(
eachStringLiteral -> {
output += mapOfStringAndNumber.get(eachStringLiteral) + literal;
}
);
Where inputString is:
String inputString = "1+3+5";
however, the compiler complains and I don't know why:
The method map(Function) in the type Stream is not applicable for the arguments (( eachStringLiteral) -> {})
I also need some help in order to understand the syntax in
Function<? super String,? extends R>.
Update
This is whole code illustrating what I am trying to achieve:
HashMap<String,Double> mapOfStringAndNumber=new HashMap<String,Double>();
mapOfStringAndNumber.put("1",270.5);
mapOfStringAndNumber.put("2",377.5);
mapOfStringAndNumber.put("3",377.5);
String inputString="1+3+5";
String literal="+";
String output;
java.util.stream.Stream.of(inputString.split("+")).map(eachStringLiteral->
output+=mapOfStringAndNumber.get(eachStringLiteral)+literal
Assuming that you provide a Double value to each input String in your map mapOfStringAndNumber, you could use Pattern#splitAsStream(CharSequence input) to split your input String directly as a Stream and use Collectors.joining(CharSequence delimiter) to build your output with + as delimiter, so your final code could be:
Map<String,Double> mapOfStringAndNumber = new HashMap<>();
mapOfStringAndNumber.put("1",270.5);
mapOfStringAndNumber.put("3",377.5);
mapOfStringAndNumber.put("5",377.5);
String inputString = "1+3+5";
String output = Pattern.compile("\\+")
.splitAsStream(inputString)
.map(mapOfStringAndNumber::get)
.map(d -> Double.toString(d))
.collect(Collectors.joining("+"));
System.out.println(output);
Output:
270.5+377.5+377.5
I have a couple of suggestions for your code:
{}-block and you want to create a Function (not a Runnable, Consumer or similar) you have to return something.Integer.parseInt(String) instead of a Map of Strings to Integersoutput from within a Stream. That could lead to concurrancy issues.literal?My example code for your usecase would look like this:
String inputString="1+3+5";
return
// split input and create stream
Stream.of(inputString.split("\\+"))
// convert each item to Integer
.mapToInt(Integer::parseInt)
// sum up everything
.sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With