Lambda capture as const reference?

Is it possible to capture by const reference in a lambda expression? I want the assignment marked below to fail, for example: #include <algorithm> #include <string> using namespace std; int main() { string strings[] = { “hello”, “world” }; static const size_t num_strings = sizeof(strings)/sizeof(strings[0]); string best_string = “foo”; for_each( &strings[0], &strings[num_strings], [&best_string](const string& s) … Read more

Does a lambda expression create an object on the heap every time it’s executed?

When I iterate over a collection using the new syntactic sugar of Java 8, such as myStream.forEach(item -> { // do something useful }); Isn’t this equivalent to the ‘old syntax’ snippet below? myStream.forEach(new Consumer<Item>() { @Override public void accept(Item item) { // do something useful } }); Does this mean a new anonymous Consumer … Read more

Filter values only if not null using lambda in Java8

I have a list of objects say car. I want to filter this list based on some parameter using Java 8. But if the parameter is null, it throws NullPointerException. How to filter out null values? Current code is as follows requiredCars = cars.stream().filter(c -> c.getName().startsWith(“M”)); This throws NullPointerException if getName() returns null. 6 Answers … Read more

Java “lambda expressions not supported at this language level”

I was testing out some new features of Java 8 and copied the example into my IDE (Eclipse originally, then IntelliJ) as shown here Eclipse offered no support whatsoever for lambda expressions, and IntelliJ kept reporting an error Lambda expressions not supported at this language level I would like to know if this is a … Read more

How to use a Java8 lambda to sort a stream in reverse order?

I’m using java lambda to sort a list. how can I sort it in a reverse way? I saw this post, but I want to use java 8 lambda. Here is my code (I used * -1) as a hack Arrays.asList(files).stream() .filter(file -> isNameLikeBaseLine(file, baseLineFile.getName())) .sorted(new Comparator<File>() { public int compare(File o1, File o2) { … Read more