Created
November 13, 2012 21:56
-
-
Save jeanlaurent/4068672 to your computer and use it in GitHub Desktop.
Fun With Lambda in jdk8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need a jdk8, with guava & fest assert to run the code.