Skip to content

Instantly share code, notes, and snippets.

@eskatos
Created October 14, 2014 10:28
Show Gist options
  • Save eskatos/f46bae317fbce5617063 to your computer and use it in GitHub Desktop.
Save eskatos/f46bae317fbce5617063 to your computer and use it in GitHub Desktop.
package qi4j;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Stream;
import org.junit.Test;
import static java.util.stream.Collectors.toList;
public class PropertyStreamTest
{
interface Property<T>
{
T get();
}
interface Student
{
Property<String> name();
}
List<Student> students = Collections.EMPTY_LIST;
// ========================================================================
// Here is what works out of the box
@Test
public void lambda()
{
List<String> names = students.stream()
.map( student -> student.name().get() )
.filter( name -> name.startsWith( "A" ) )
.collect( toList() );
}
@Test
public void double_method_reference()
{
List<String> names = students.stream()
.map( Student::name ).map( Property::get )
.filter( name -> name.startsWith( "A" ) )
.collect( toList() );
}
// ========================================================================
// Approach using a custom Collector
// (its accumulator function call Property::get)
@Test
public void customCollector()
{
List<String> names = students.stream()
.map( Student::name )
.filter( name -> name.get().startsWith( "A" ) )
.collect( toValuesList() );
}
static <T> Collector<Property<T>, ?, List<T>> toValuesList()
{
return Collector.of(
ArrayList::new,
(left, right) -> left.add( right.get() ),
(left, right) ->
{
left.addAll( right );
return left;
}
);
}
// ========================================================================
// Approach using a custom Stream
// (adds a mapToValue(..) methods, in the same vein as mapToLong(..) & co ...)
@Test
public void customStream()
{
List<String> names = stream( students )
.mapToValue( Student::name )
.filter( name -> name.startsWith( "A" ) )
.collect( toList() );
}
static <T> CustomStream<T> stream( Collection<T> collection )
{
// Should return a wrapped Stream with the added mapToValue method
return null;
}
interface CustomStream<T>
extends Stream<T>
{
<R> Stream<R> mapToValue( Function<? super T, ? extends Property<R>> mapper );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment