Skip to content

Instantly share code, notes, and snippets.

@hkmoon
Last active September 15, 2015 08:57
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 hkmoon/c123e7e45fa4eaaf3a87 to your computer and use it in GitHub Desktop.
Save hkmoon/c123e7e45fa4eaaf3a87 to your computer and use it in GitHub Desktop.
Java 8: stream(), map() and collect()
// In Java 8, there are stream(), map() and collect() for better collection manipulation
ArrayList<String> list = new ArrayList<>();
for(Person person : people)
{
list.add( person.getNickName() );
}
// The above code is shortened with the below
List<String> list = people.stream().map( Person::getNickName ).collect( Collectors.toList() );
// The collection
ArrayList<Person> people = new ArrayList<>();
people.add( new Person( "Tom Hanks", "Tommy") );
people.add( new Person( "Anthony Hopkins", "Tony") );
people.add( new Person( "Benjamin Franklin", "Ben") );
// public class Person
// {
// final String name;
// final String nickName;
// public Person( String name, String nickName )
// {
// this.name = name;
// this.nickName = nickName;
// }
// public String getName()
// {
// return name;
// }
// public String getNickName()
// {
// return nickName;
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment