Retrieving a List from a java.util.stream.Stream in Java 8

What you are doing may be the simplest way, provided your stream stays sequential—otherwise you will have to put a call to sequential() before forEach. [later edit: the reason the call to sequential() is necessary is that the code as it stands (forEach(targetLongList::add)) would be racy if the stream was parallel. Even then, it will … Read more

Join/Where with LINQ and Lambda

I find that if you’re familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors: var id = 1; var query = from post in database.Posts join meta in database.Post_Metas on post.ID equals meta.Post_ID where post.ID == id select new { Post = post, … Read more

Retrieving Property name from lambda expression

I recently did a very similar thing to make a type safe OnPropertyChanged method. Here’s a method that’ll return the PropertyInfo object for the expression. It throws an exception if the expression is not a property. public PropertyInfo GetPropertyInfo<TSource, TProperty>( TSource source, Expression<Func<TSource, TProperty>> propertyLambda) { Type type = typeof(TSource); MemberExpression member = propertyLambda.Body as … Read more

Java 8 Lambda function that throws exception?

You’ll need to do one of the following. If it’s your code, then define your own functional interface that declares the checked exception: @FunctionalInterface public interface CheckedFunction<T, R> { R apply(T t) throws IOException; } and use it: void foo (CheckedFunction f) { … } Otherwise, wrap Integer myMethod(String s) in a method that doesn’t … Read more

What is the difference between a ‘closure’ and a ‘lambda’?

A lambda is just an anonymous function – a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but … Read more