Skip to content

Instantly share code, notes, and snippets.

@jeanlaurent
Created November 13, 2012 21:56
Show Gist options
  • Save jeanlaurent/4068672 to your computer and use it in GitHub Desktop.
Save jeanlaurent/4068672 to your computer and use it in GitHub Desktop.
Fun With Lambda in jdk8
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.collect.FluentIterable.from;
import static java.util.Arrays.asList;
import static java.util.streams.Streams.stream;
import static org.fest.assertions.Assertions.assertThat;
public class FunWithLambda {
@Test
public void shouldFilterASimpleCollection() {
List<String> stringsAsList = asList("foo", "bar", "qix", "baz");
ArrayList<String> resultList = stream(stringsAsList).filter(x -> x.startsWith("b")).into(new ArrayList<String>());
assertThat(resultList).containsOnly("bar", "baz");
}
@Test
public void shouldFilterASimpleCollectionWithoutStupidStreams() {
List<String> stringsAsList = asList("foo", "bar", "qix", "baz");
List<String> resultsLists = stringsAsList.stream().filter(x -> x.startsWith("b")).into(new ArrayList<String>());
assertThat(resultsLists).containsOnly("bar", "baz");
}
@Test
public void shouldFilterWithGuava() {
List<String> stringsAsList = asList("foo", "bar", "qix", "baz");
Iterable<String> resultsLists = from(stringsAsList).filter(x -> x.startsWith("b"));
assertThat(resultsLists).containsOnly("bar", "baz");
}
@Test
public void shouldReduceASimpleCollection() {
List<Integer> stringsAsList = asList(1, 2, 3, 4, 5);
Integer sum = stream(stringsAsList).reduce((x, y) -> x + y).get();
assertThat(sum).isEqualTo(15);
}
}
@jeanlaurent
Copy link
Author

You need a jdk8, with guava & fest assert to run the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment