[JAVA] Find the average age from List <Person>.

Table of Contents ⇒ Java Algorithm Library-Artery-Sample


package jp.avaj.lib.algo;

import java.util.ArrayList;
import java.util.List;

import jp.avaj.lib.test.L;

 *  List<Person>Find the average age from.
 *・ Target data from Person(age)You need to define ArCreator to retrieve.
 *-In the first method, the convert method is implemented to extract the age..
 *-However, this method is troublesome because an implementation is created for each field to be extracted..
 *-In the second method, a general-purpose ArCreatorByName is created and the field name is specified..
 *・ It is possible to prevent the number of ArCreator implementations from increasing unnecessarily..
public class Q01_07 {
  public static void main(String[] args) throws Exception {
    List<Person> list = createList();

    //Definition of ArCreator-First way
    ArCreator<Person,Integer> creator = new ArCreator<Person,Integer>() {
      public Integer convert(Person obj) throws Exception {
        return obj.getAge();
    //Find the average value

    //Definition of ArCreator-Second method
    creator = new ArCreatorByName<Person,Integer>("age");
    //Find the average value

  /**Create personal information*/
  private static List<Person> createList() {
    List<Person> list = new ArrayList<Person>();
    list.add(new Person("a",25));
    list.add(new Person("b",30));
    list.add(new Person("c",28));
    list.add(new Person("d",22));
    list.add(new Person("e",38));
    return list;

  /**Person information class(Only name and age..) */
  static class Person {
    public Person(String name,int age) {
      this.name = name;
      this.age = age;
    private String name;
    private int age;
    public String getName() {
      return name;
    public void setName(String name) {
      this.name = name;
    public int getAge() {
      return age;
    public void setAge(int age) {
      this.age = age;

The result is as follows.



Recommended Posts

Find the average age from List <Person>.
Aggregate the number of people every 10 years from List <Person>
Find the difference between List types
Find the difference from a multiple of 10
Find the subnet mask from the network prefix length
How to find the total score and average score
ArrayList and the role of the interface seen from List
Extract a specific element from the list of objects
Find the address class and address type from the IP address with Java