使用java8流创建另一个对象列表 [英] Create list of object from another using java8 streams

查看:108
本文介绍了使用java8流创建另一个对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解Java 8流。
我有两个类:

I'm trying to understand Java 8 streams. I have two classes:

public class UserMeal {
    protected final LocalDateTime dateTime;

    protected final String description;

    protected final int calories;

    public UserMeal(LocalDateTime dateTime, String description, int calories) {
        this.dateTime = dateTime;
        this.description = description;
        this.calories = calories;
    }

    public LocalDateTime getDateTime() {
        return dateTime;
    }

    public String getDescription() {
        return description;
    }

    public int getCalories() {
        return calories;
    }
}

和:

public class UserMealWithExceed {
    protected final LocalDateTime dateTime;

    protected final String description;

    protected final int calories;

    protected final boolean exceed;

    public UserMealWithExceed(LocalDateTime dateTime, String description, int calories, boolean exceed) {
        this.dateTime = dateTime;
        this.description = description;
        this.calories = calories;
        this.exceed = exceed;
    }
}

超过字段应指明一整天的卡路里总和。该字段对于当天的所有条目都是相同的。

The exceed field should indicate whether the sum of calories for the entire day. This field is the same for all entries for that day.

我尝试从 List< UserMeal>获取对象mealList ,按天分组,计算一段时间内的卡路里,并创建列表< UserMealWithExceed>

I try to get object from List<UserMeal> mealList, group by the day, calculate calories for a period of time, and create List<UserMealWithExceed>:

public static List<UserMealWithExceed>  getFilteredMealsWithExceeded(List<UserMeal> mealList, LocalTime startTime, LocalTime endTime, int caloriesPerDay) {

    return mealList.stream()
            .filter(userMeal -> userMeal.getDateTime().toLocalTime().isAfter(startTime)&&userMeal.getDateTime().toLocalTime().isBefore(endTime))
            .collect(Collectors.groupingBy(userMeal -> userMeal.getDateTime().getDayOfMonth(),
                         Collectors.summingInt(userMeal -> userMeal.getCalories())))
            .forEach( ????? );
}

但我不明白如何在<$ c $中创建新对象c> forEach 并返回集合。

but I don't understand how to create new object in forEach and return collection.

我在伪代码中的看法:

.foreach( 
    if (sumCalories>caloriesPerDay)
    {return new UserMealWithExceed(userMeal.getdateTime, usermeal.getDescription, usermeal.getCalories, true);}
    else
    {return new UserMealWithExceed(userMeal.getdateTime, usermeal.getDescription, usermeal.getCalories, false)
    }
)//foreach


推荐答案

如果要迭代列表并使用已转换对象创建新列表,则应使用 map()流的功能+ collect()。在下面的示例中,我找到姓氏为l1的所有人,并且每个人映射到新的Employee实例。

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all persons with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

}

这篇关于使用java8流创建另一个对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆