Skip to content

Instantly share code, notes, and snippets.

@kretes
Created May 15, 2014 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kretes/c4fd8197efaaf0375733 to your computer and use it in GitHub Desktop.
Save kretes/c4fd8197efaaf0375733 to your computer and use it in GitHub Desktop.
private Function<Color, Color> filter;
@Test
public void j8Test() throws Exception {
Optional<Integer> optional = stream().filter((a) -> a > 10).findFirst();
optional.
Integer result = optional.map(i -> i * i).orElse(-1);
System.out.println(result);
Map<Integer, List<Integer>> grouppedBy = stream().collect(groupingBy(Function.<Integer>identity()));
System.out.println(grouppedBy);
Map<Integer, Optional<Integer>> grouppedAndSummed = stream().collect(groupingBy(Function.<Integer>identity(), reducing((Integer a, Integer b) -> a + b)));
System.out.println(grouppedAndSummed);
Integer sum = stream().collect(Collectors.summingInt((a) -> a));
System.out.println(sum);
Double avg = stream().collect(Collectors.averagingInt((a) -> a));
System.out.println(avg);
Integer product = stream().collect(Collectors.reducing(1, (a, b) -> a * b));
System.out.println(product);
Integer product2 = stream().reduce(1, (a, b) -> a * b);
System.out.println(product2);
Integer sumOfages = personStream().collect(Collectors.summingInt((Person p) -> p.age));
System.out.println(sumOfages);
Integer sumOfages2 = personStream().collect(Collectors.summingInt(Person::getAge));
System.out.println(sumOfages2);
Function<Person,Integer> f = (Person p) -> p.age;
ToIntFunction<Person> ff = (Person p) -> p.age;
Integer sumOfages3 = personStream().collect(Collectors.summingInt(ff));
System.out.println(sumOfages3);
Integer sumOfages4 = personStream().mapToInt(Person::getAge).sum();
System.out.println(sumOfages4);
personStream().mapToInt(Person::getAge).sum();
// Arrays.asList(new Character('a')).stream().
Stream<Character> characterStream = "aasdqweasd".chars().mapToObj(i -> Character.valueOf((char) i));
}
private Stream<Person> personStream() {
return Arrays.asList(new Person(1), new Person(2)).stream();
}
class Person {
public int age;
Person(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
private Stream<Integer> stream() {
return Arrays.asList(1, 2, 3, 4, 3, 4, 2, 3, 4).stream();
}
public void setFilters(final Function<Color, Color>... filters) {
filter =
Stream.of(filters)
.reduce((filter, next) -> filter.compose(next))
.orElse(color -> color);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment