Guest User

Untitled

a guest
Jul 17th, 2015
776
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.StringJoiner;
  4. import java.util.stream.Collectors;
  5.  
  6. public class Example {
  7.  
  8.     public static void main(String[] args) {
  9.  
  10.         // String.join expects arguments of type CharSequence, or Iterable<CharSequence>
  11.         // For example...
  12.         // List<String> names = Arrays.asList("Tom", "Dick", "Harry");
  13.         // String joined = String.join(",", names);
  14.  
  15.         // This program demonstrates how to join other kinds of objects.
  16.  
  17.         List<Person> people = Arrays.asList(
  18.                 new Person("Tom", 30),
  19.                 new Person("Dick", 27),
  20.                 new Person("Harry", 33));
  21.  
  22.         // Approach 1
  23.         String joined = people.stream()
  24.                 .map(object -> object.getName())
  25.                 .collect(Collectors.joining(","));
  26.         System.out.println("Approach 1. " + joined);
  27.  
  28.         // Approach 2
  29.         StringJoiner joiner = new StringJoiner(",");
  30.         people.stream().map(Person::getName).forEach(joiner::add);
  31.         System.out.println("Approach 2. " + joiner.toString());
  32.     }
  33.  
  34. }
  35.  
  36. class Person {
  37.     private String name;
  38.     private int age;
  39.  
  40.     public Person(String name, int age) {
  41.         this.name = name;
  42.         this.age = age;
  43.     }
  44.  
  45.     public String getName() {
  46.         return name;
  47.     }
  48.  
  49.     public void setName(String name) {
  50.         this.name = name;
  51.     }
  52.  
  53.     public int getAge() {
  54.         return age;
  55.     }
  56.  
  57.     public void setAge(int age) {
  58.         this.age = age;
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment