Table of Contents ⇒ Java Algorithm Library-Artery-Sample
Q01_07.java
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>() {
@Override
public Integer convert(Person obj) throws Exception {
return obj.getAge();
}
};
//Find the average value
L.p(ArList.avg(list,creator)+"");
//Definition of ArCreator-Second method
creator = new ArCreatorByName<Person,Integer>("age");
//Find the average value
L.p(ArList.avg(list,creator)+"");
}
/**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.
result.txt
28.6
28.6
Recommended Posts