当前位置: 首页 > 知识库问答 >
问题:

使用Java8流从另一个对象创建对象列表

周鸿运
2023-03-14

我试图理解Java8流。我有两门课:

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;
    }
}

except字段应指示全天的卡路里总量是否为。该字段与当天的所有条目相同。

我试图从列表中获取对象

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( ????? );
}

但是我不明白如何在中为每个创建新对象并返回集合。

我如何看待伪代码:

.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

共有3个答案

鄢朝斑
2023-03-14

@Rafael Teles对解决方案的补充。语法糖Collectors.mapping一步完成同样的操作:

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

详细的例子可以在这里找到

咸星波
2023-03-14

您可能正在寻找的是map()。您可以通过以下方式将流中的对象“转换”为另一个:

...
 .map(userMeal -> new UserMealExceed(...))
...
公冶子琪
2023-03-14

如果要迭代列表并创建包含“转换”对象的新列表,应使用streamcollect()map()函数。在下面的示例中,我找到姓为“l1”的所有人以及我要“映射”到新员工实例的每个人。

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;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

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

    // Getter & Setter
}
 类似资料:
  • 我有一个学生名单a和学生名单B。 学生对象包含如下字段:否、年龄、城市、出生日期、工资 我的列表A包含这些对象 我的列表B包含这些对象 我想做的是提取ListA有但listB没有的学生对象,以及ListA和listB有但薪水不同的学生对象(如否、年龄、城市)。我还想写工资差异。 我想在java 8中使用流api。首先,我想将students对象提取到列表中,但我现在可以提取常见的student对象

  • 我有一个要求,我需要根据2个条件从另一个列表中创建一个对象列表。对象应处于会话中或处于活动状态。[这个问题与使用java8流从另一个对象创建对象列表有着模糊的联系 主要类别: 任何帮助都将不胜感激。

  • 问题内容: 我有以下Java6和Java8代码: Java8中有什么方法可以使用Lambda以更简洁的方式处理前一个问题? 问题答案: 流绑定到给定的可迭代/集合,因此您不能真正地“并行”迭代两个集合。 一种解决方法是创建索引流,但不一定比for循环有所改进。流版本可能如下所示:

  • 我想从另一个对象创建一个< code>ExampleInterface对象,但只保留< code>ExampleInterface包含的那些属性。 是否可以不手动复制每个密钥? 然后呢 提前谢谢你。

  • 我有两个Java类,Product和ProductReview。ProductReview除了变量long id和String review外,还有一个名为Product的变量,该变量应包含类Product中的一个对象。例子: Products类有私有变量long id、String name和List评论(它也从Product评论类中获取评论)。产品类与Product评论有一对多的关联,反之亦然