Skip to content
Advertisement

Tag: functional-programming

returning early from a method if an Optional is empty

Is there a more functional way to return early from a method if an Optional is empty than this? What I’m looking for is something like Optional.ifPresentOrElse, but I can’t use that in this case, because the lambda arguments it takes (Consumer and Runnable) both have void return types. If the lambda arguments were instead of type Function, and the

How to implement the Elvis operator in Java 8?

I have the classic “Elvis operator” case, where I’m calling methods that each may return null and chaining them together: In Java 8, the most faithful implementation I’ve found is something like this: I wish that Java’s Optional had something akin to the elvis operator: So that I wouldn’t have to wrap each return value: Is there a more efficient

Count the same items in a row in Java 8 Stream API

I have a bean and a stream and want to apply some intermediate operation to the stream that returns another stream of objects of TokenBag. In this example there must be two: (“a”, 3), (“b”, 3) and (“a”, 2). Please think it as a very simplistic example. In real there will be much more complicated logic than just counting the

Java strange class cast exception

Could anyone help me understand why in 1 situation I do not have ClassCastException? At least String::trim is not a MagicFunction. Answer So, method references (like String::trim) are a bit weird; unlike most expressions in Java, they don’t really have a type of their own. Something like this: won’t even compile, because it doesn’t give the compiler enough information about

Map getOrDefault VS getOrUseSupplier

I am starting to learn lambdas and i do not understand why java Map has: and not(working just the same, but if value is absent, then defaultValue will be taken from supplier): Adventages i currently see of current solution: defaultValue does not have to be a final/effectively final value looks simpler & no need to know lambda syntax Disadventages: If

Java Stream equivalent of LINQ SelectMany()

What’s the Java 8 Stream equivalent of LINQ’s SelectMany? For example, in C#, if I have Dictionary<string, List<Tag>> tags that I want to turn into an IEnumerable<Tag> (a flat enumerable of all the tags in the dictionary), I would do tags.SelectMany(kvp => kvp.Value). Is there a Java equivalent for a Map<String, List<Tag>> that would yield a Stream<Tag>? Answer You’re looking

Advertisement