Monday, November 3, 2014

Java each group pro



Get Total age by gender

import java.time.LocalDate;
import java.time.chrono.IsoChronology;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Main 
{
 public static void main(String[] args) 
{
      List roster = createRoster();
      System.out.println("Total age by gender:");
      MapInteger> totalAgeByGender =
          roster
              .stream()
              .collect(
                   Collectors.groupingBy(
                       Person::getGender,                      
                       Collectors.reducing(
                           0,
                           Person::getAge,
                           Integer::sum)));
          ListInteger>>
          totalAgeByGenderList = 
          new ArrayList<>(totalAgeByGender.entrySet());
          totalAgeByGenderList
          .stream()
          .forEach(e -> 
              System.out.println("Gender: " + e.getKey() +
                  ", Total Age: " + e.getValue()));
             }
                public static List createRoster() 
                {
                  List roster = new ArrayList<>();
        roster.add(
            new Person(
            "Fred",
            IsoChronology.Instance.date(1980, 6, 20),
            Person.Sex.Male,"fredexample"));
        roster.add(
            new Person(
            "Jane",
            IsoChronology.Instance.date(1990, 7, 15),
            Person.Sex.Female, "janeexample"));
        roster.add(
            new Person(
            "George",
            IsoChronology.Instance.date(1991, 8, 13),
            Person.Sex.Male, "georgeexample "));
        roster.add(
            new Person(
            "Bob",
            IsoChronology.Instance.date(2000, 9, 12),
            Person.Sex.Male, "bobexample "));
        return roster;
    }
}
class Averager implements IntConsumer
{
    private int total = 0;
    private int count = 0;
  public double average() 
   {
        return count > 0 ? ((double) total)/count : 0;
    }
  public void accept(int i) { total += i; count++; }
  public void combine(Averager other) 
 {
        total += other.total;
        count += other.count;
    }
}
class Person 
{
 public enum Sex 
 {
      Male, Female
  }
  String name; 
  LocalDate birthday;
  Sex gender;
  String emailAddress;
            Person(String nameArg, LocalDate birthdayArg,Sex genderArg, String emailArg) 
{
      name = nameArg;
      birthday = birthdayArg;
      gender = genderArg;
      emailAddress = emailArg;
  }  
             public int getAge() 
             {
      return birthday
          .until(IsoChronology.Instance.dateNow())
          .getYears();
   }
              public void printPerson() 
              {
      System.out.println(name + ", " + this.getAge());
    }
    public Sex getGender() 
   {
      return gender;
    }
   public String getName() 
   {
      return name;
    }
            public String getEmailAddress() 
            {
      return emailAddress;
  }
  public LocalDate getBirthday() 
  {
      return birthday;
   }
 public static int compareByAge(Person a, Person b) 
 {
      return a.birthday.compareTo(b.birthday);
  }
          }

Get highest value for each group

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class Main 
{
  public static void main(String...args)
  {
    Map> o = 
    Food.menu.stream().collect(
        Collectors.groupingBy(Food::getType,
        Collectors.reducing((Food d1, Food d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2)));
     System.out.println(o);
    }
}
enum Type { Meat, Fish, Other }
class Food 
{
            private final String name;
  private final boolean vegetarian;
  private final int calories;
  private final Type type;
 
  public Food(String name, boolean vegetarian, int calories, Type type)
  {
      this.name = name;
      this.vegetarian = vegetarian;
      this.calories = calories;
      this.type = type;
  }
             public String getName() 
            {
      return name;
  }
             public boolean isVegetarian() 
            {
      return vegetarian;
  }
             public int getCalories() 
            {
      return calories;
  }
             public Type getType() 
            {
      return type;
   }
  public String toString() 
 {
      return name;
  }
             public static final List menu =
          Arrays.asList( new Food("pork", false, 1800, Type.Meat),
                         new Food("beef", false, 7100, Type.Meat),
                         new Food("chicken", false, 1400, Type.Meat),
                         new Food("french fries", true, 1530, Type.Other),
                         new Food("rice", true, 3510, Type.Other),
                         new Food("season fruit", true, 1120, Type.Other),
                         new Food("pizza", true, 5150, Type.Other),
                         new Food("prawns", false, 1400, Type.Fish),
                         new Food("salmon", false, 4150, Type.Fish));
}

Get max value in each group

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
           public class Main 
           {
  public static void main(String...args)
  {
    Map o =  
    Food.menu.stream().collect(
        Collectors.groupingBy(Food::getType,
         Collectors.collectingAndThen(
         Collectors.reducing((Food d1, Food d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2),
                    Optional::get)));
        System.out.println(o);
    }
}
enum Type { Meat, Fish, Other }
class Food 
{
            private final String name;
  private final boolean vegetarian;
  private final int calories;
  private final Type type;
          public Food(String name, boolean vegetarian, int calories, Type type) 
          {
      this.name = name;
      this.vegetarian = vegetarian;
      this.calories = calories;
      this.type = type;
  }
          public String getName() 
           {
      return name;
  }
 
public boolean isVegetarian() 
 {
      return vegetarian;
  }
          public int getCalories() 
           {
      return calories;
  }
         public Type getType() 
          {
      return type;
  }
         public String toString() 
           {
      return name;
  }
         public static final List menu =
          Arrays.asList( new Food("pork", false, 1800, Type.Meat),
                         new Food("beef", false, 7100, Type.Meat),
                         new Food("chicken", false, 1400, Type.Meat),
                         new Food("french fries", true, 1530, Type.Other),
                         new Food("rice", true, 3510, Type.Other),
                         new Food("season fruit", true, 1120, Type.Other),
                         new Food("pizza", true, 5150, Type.Other),
                         new Food("prawns", false, 1400, Type.Fish),
                         new Food("salmon", false, 4150, Type.Fish));
}

No comments:

Post a Comment