There are many approaches, here is one.
Map<String, Integer> map = Map.of(" ", 18, "foo", 14, "abcd",
20, "ab", 10, "efgh", 3, "rstuv", 14);
Then I would define a Predicate<Entry<String, Integer>>
to reduce the clutter of the stream construct. Note that since you are checking for length < 3
the condition for a single space can be omitted. If you meant check for a blank String, you can use !val.getKey().isBlank()
as the condition.
reduce
takes an initial argument followed by a BinaryOperator
as an accumulator. In this case the accumulation is a concatenation of the mapped strings. String::concat
meets the requirements and is used here to fulfill the operation.
Predicate<Entry<String, Integer>> check =
val -> val.getValue() >= 10
&& val.getKey().length() > 3;
Then it is just a matter of streaming the EntrySet
.
String result = map.entrySet().stream().filter(check)
.map(e -> e.getKey().toLowerCase() + " - " + e.getValue() + "\n")
.reduce("", String::concat);
Systemm.out.print(result);
Prints the following.
abcd - 20
rstuv - 14