Java – streams: how maps in streams work
•
Java
In order to better understand the map function in streams, I tried this:
String inputString="1+3+5"; Stream.of(inputString.split("\\+")).map( eachStringLiteral -> { output += mapOfStringAndNumber.get(eachStringLiteral) + literal; } );
Inputstring is:
String inputString = "1+3+5";
However, the compiler complains and I don't know why:
I need some help to understand grammar
Function & lt;? Super string,? Extension r >
to update
This is the complete code, which explains the goal I want 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
Solution
Assuming that you provide a double value for each input string in map mapofstringandnumber, you can directly split the input string into streams using pattern #splitasstream (charsequence input) and use collectors Joining (charsequence delimiter) builds the output with the as delimiter, so your final code may 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码