Guest User

Untitled

a guest
Jun 19th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. package net.smcrow.sandbox.streams;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6. import java.util.stream.Collectors;
  7.  
  8. public class CreateListsOfProperties {
  9. private static final List<Person> PEOPLE = List.of(new Person("Sarah", 29),
  10. new Person("John", 16),
  11. new Person("Mary", 21),
  12. new Person("Susan", 55));
  13.  
  14. public static void main(String... args) {
  15. System.out.println("Without Streams");
  16. withoutStreams();
  17.  
  18. System.out.println("With Streams");
  19. withStreams();
  20. }
  21.  
  22. private static void withoutStreams() {
  23. List<String> names = new ArrayList<>();
  24. List<Integer> ages = new ArrayList<>();
  25.  
  26. for (Person person : PEOPLE) {
  27. names.add(person.getName());
  28. ages.add(person.getAge());
  29. }
  30.  
  31. // To print the results you most likely used something like StringUtils.join, or Guava's Joiner
  32. // Or you did messy things like this:
  33. System.out.println("Names: " + String.join(", ", names.toArray(new String[0])));
  34. System.out.println("Ages: " + Arrays.toString(ages.toArray()).replace("[", "").replace("]", ""));
  35. }
  36.  
  37. private static void withStreams() {
  38. List<String> names = PEOPLE.stream().map(Person::getName).collect(Collectors.toList());
  39. List<Integer> ages = PEOPLE.stream().map(Person::getAge).collect(Collectors.toList());
  40.  
  41. System.out.println("Names: " + names.stream().collect(Collectors.joining(", ")));
  42. System.out.println("Ages: " + ages.stream().map(Object::toString).collect(Collectors.joining(", ")));
  43. }
  44.  
  45. private static class Person {
  46. private String name;
  47. private int age;
  48.  
  49. Person(String name, int age) {
  50. this.name = name;
  51. this.age = age;
  52. }
  53.  
  54. String getName() {
  55. return name;
  56. }
  57.  
  58. int getAge() {
  59. return age;
  60. }
  61. }
  62. }
Add Comment
Please, Sign In to add comment