简体   繁体   English

java 收集列表忽略

[英]java collec to list ignored

I am trying to write lambda in java that filter list by month and add data in the current month to the new list but when I try to collect the data I get an error collect is ignored.我正在尝试在 java 中编写 lambda 按月过滤列表并将当前月份的数据添加到新列表但是当我尝试收集数据时出现错误 collect is ignored。

public String getMonthlyExpensesNew() {
        Functions functions = new Functions();
        List<ShoppingMgnt> monthlyData = new ArrayList<>();
        try {
            monthlyData = getRecordsAsList();

            monthlyData.stream().filter(date -> functions.checkForCurrentMonth(date.getPurchaseDate())).collect(Collectors.toList());

        }catch (SQLException sqlException){
            System.err.println("Error in getMonthlyExpensesNew");
        }

        return String.valueOf(monthlyData);
    }


public boolean checkForCurrentMonth(String givenDate){
        LocalDate currentDate = LocalDate.now();
        LocalDate monthToCheck = LocalDate.parse(givenDate);
        return currentDate.getMonth().equals(monthToCheck.getMonth());
    }

Your initial code:您的初始代码:

monthlyData.stream()
   .filter(date -> functions.checkForCurrentMonth(date.getPurchaseDate()))
   .collect(Collectors.toList());

Within this line the collect operation returns a List .在此行中, collect操作返回一个List You should store this List into your monthlyData reference to be returned later.您应该将此List存储到您的monthlyData引用中,以便稍后返回。 So you should write like this:所以你应该这样写:

monthlyData = monthlyData.stream()
    .filter(date -> functions.checkForCurrentMonth(date.getPurchaseDate()))
    .collect(Collectors.toList());

your final function will be as follow:您最终的 function 将如下所示:

public String getMonthlyExpensesNew() {
    Functions functions = new Functions();
    List<ShoppingMgnt> monthlyData = new ArrayList<>();
    try {
        monthlyData = getRecordsAsList();
        //put the returned list in the same defined list
        monthlyData = monthlyData.stream()
        .filter(date -> functions.checkForCurrentMonth(date.getPurchaseDate()))
        .collect(Collectors.toList());

    }catch (SQLException sqlException){
        System.err.println("Error in getMonthlyExpensesNew");
    }
    //the return with updated list  
    return String.valueOf(monthlyData);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM