How is “int main(){(([](){})());}” valid C++?

I recently came across the following esoteric piece of code. int main(){(([](){})());} Reformat it as follows to make it more readable: int main(){ (([](){})()); // Um… what?!?! } But I can’t get my head around how (([](){})()) is valid code. It doesn’t look like function pointer syntax. It can’t be some operator overloading trick. The … Read more

Using Java 8’s Optional with Stream::flatMap

The new Java 8 stream framework and friends make for some very concise Java code, but I have come across a seemingly-simple situation that is tricky to do concisely. Consider a List<Thing> things and method Optional<Other> resolve(Thing thing). I want to map the Things to Optional<Other>s and get the first Other. The obvious solution would … Read more

Filter Java Stream to 1 and only 1 element

I am trying to use Java 8 Streams to find elements in a LinkedList. I want to guarantee, however, that there is one and only one match to the filter criteria. Take this code: public static void main(String[] args) { LinkedList<User> users = new LinkedList<>(); users.add(new User(1, “User1”)); users.add(new User(2, “User2”)); users.add(new User(3, “User3”)); User … Read more

Why does C++11’s lambda require “mutable” keyword for capture-by-value, by default?

Short example: #include <iostream> int main() { int n; [&](){n = 10;}(); // OK [=]() mutable {n = 20;}(); // OK // [=](){n = 10;}(); // Error: a by-value capture cannot be modified in a non-mutable lambda std::cout << n << “\n”; // “10” } The question: Why do we need the mutable keyword? It’s … Read more

Java 8 Streams: multiple filters vs. complex condition

Sometimes you want to filter a Stream with more than one condition: myList.stream().filter(x -> x.size() > 10).filter(x -> x.isCool()) … or you could do the same with a complex condition and a single filter: myList.stream().filter(x -> x.size() > 10 && x -> x.isCool()) … My guess is that the second approach has better performance characteristics, … Read more

A positive lambda: ‘+[]{}’ – What sorcery is this? [duplicate]

This question already has an answer here: Resolving ambiguous overload on function pointer and std::function for a lambda using + (unary plus) (1 answer) Closed 8 years ago. In Stack Overflow question Redefining lambdas not allowed in C++11, why?, a small program was given that does not compile: int main() { auto test = []{}; … Read more