Create a new list with values ​​from fields from an existing list

Let's say there is a class:

class Person
{
   String name;
   int age;
   City location;
}

Is there any library that will allow me to create a list of lines containing each name from a list of persons on one line instead of creating a new list and scrolling through another list?

Sort of:

List<Person> people = getAllOfThePeople();
List<String> names = CoolLibrary.createList("name", people);

Instead

List<Person> people = getAllOfThePeople();
List<String> names = new LinkedList<String>();
for(Person person : people)
{
    names.add(person.getName());
}
+4
source share
2 answers

You can use Java 8 with lambda expressions :

List<String> listNames = people.stream().map(u -> u.getName()).collect(Collectors.toList());

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Test {
  public static void main(String args[]){
    List<Person> people = Arrays.asList(new Person("Bob",25,"Geneva"),new Person("Alice",27,"Paris"));
    List<String> listNames = people.stream().map(u -> u.getName()).collect(Collectors.toList());
    System.out.println(listNames);
  }
}
class Person
{
   private String name;
   private int age;
   private String location;

  public Person(String name, int age, String location){
    this.name = name;
    this.age = age;
    this.location = location;
  }

  public String getName(){
    return this.name;
  }

}

Exit:

[Bob, Alice]

Demo is here .

<h / "> In addition, you can define a method that will accept your list as a parameter and a function that you want to apply for each element of this list:

public static <X, Y> List<Y> processElements(Iterable<X> source, Function <X, Y> mapper) {
    List<Y> l = new ArrayList<>();
    for (X p : source) 
        l.add(mapper.apply(p));
    return l;
}

Then just do:

List<String> lNames = processElements(people, p -> p.getName()); //for the names
List<Integer> lAges = processElements(people, p -> p.getAge()); //for the ages
//etc.

, Collectors ():

Map<Integer, List<Person>> byAge = people.stream()
                                         .collect(Collectors.groupingBy(Person::getAge));
+10

Guava ( Java, ):

class Person
{
   String name;
   int age;
   City location;

  public static final Function<Person, String> getName = new Function<Person, String>() {
    public String apply(Person person) {
      return person.name;
    }
  }
}


List<Person> people = getAllOfThePeople();
List<String> names = FluentIterable.from(people).transform(Person.getName).toList();

getName public static Function Person.

+4

All Articles