Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ArrayList<Object[]> csvArray = new ArrayList<Object[]>();
- Stream<Person> people = Stream.of(new Person("Paul", 24), new Person("Mark",30), new Person("Will", 28));
- Map<Integer, List<String>> peopleByAge = people
- .collect(groupingBy(p -> p.age, mapping((Person p) -> p.name, toList())));
- System.out.println(peopleByAge);
- final List<Object[]> data = new ArrayList<>();
- data.add(new Object[]{"NL", "Rotterdam", "Kees", 38});
- data.add(new Object[]{"NL", "Rotterdam", "Peter", 54});
- data.add(new Object[]{"NL", "Amsterdam", "Suzanne", 51});
- data.add(new Object[]{"NL", "Rotterdam", "Tom", 17});
- final Map<String, List<Object[]>> map = data.stream().collect(
- Collectors.groupingBy(row -> row[0].toString() + ":" + row[1].toString()));
- for (final Map.Entry<String, List<Object[]>> entry : map.entrySet()) {
- final double average = entry.getValue().stream()
- .mapToInt(row -> (int) row[3]).average().getAsDouble();
- System.out.println("Average age for " + entry.getKey() + " is " + average);
- }
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
- public class CSVExample {
- public static void main(String[] args) {
- ArrayList<Information> csvArray = new ArrayList<>();
- csvArray.add(new Information(new Object[] {"France", "Paris", "Pierre", 34}));
- csvArray.add(new Information(new Object[] {"France", "Paris", "Madeleine", 26}));
- csvArray.add(new Information(new Object[] {"France", "Toulouse", "Sam", 34}));
- csvArray.add(new Information(new Object[] {"Italy", "Rom", "Paul", 44}));
- Map<String, List<Information>> collect = csvArray.stream().collect(Collectors.groupingBy(s -> (s.getCountry() + " " + s.getCity())));
- collect.forEach((k, v) -> System.out.println(k + " " + v.stream().collect(Collectors.averagingInt(Information::getAge))));
- }
- }
- class Information {
- private String country;
- private String city;
- private String name;
- private int age;
- public Information(Object[] information) {
- this.country = (String) information[0];
- this.city = (String) information[1];
- this.name = (String) information[2];
- this.age = (Integer) information[3];
- }
- public Information(String country, String city, String name, int age) {
- super();
- this.country = country;
- this.city = city;
- this.name = name;
- this.age = age;
- }
- public String getCountry() {
- return country;
- }
- public String getCity() {
- return city;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- @Override
- public String toString() {
- return "Information [country=" + country + ", city=" + city + ", name=" + name + ", age=" + age + "]";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement