Last active
September 15, 2015 08:57
-
-
Save hkmoon/c123e7e45fa4eaaf3a87 to your computer and use it in GitHub Desktop.
Java 8: stream(), map() and collect()
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
// 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