Java 8显示了此错误。在封闭范围内定义的局部变量itemList必须是最终的或有效的final [英] Java 8 shows this error. Local variable itemList defined in an enclosing scope must be final or effectively final

查看:4541
本文介绍了Java 8显示了此错误。在封闭范围内定义的局部变量itemList必须是最终的或有效的final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用java 8编写代码,但我迭代 List ,然后使用类别类型查找 RestaurantOrderBook 。并将 List 放入 Map 。它显示此错误:

I am writing the code using java 8 but I iterate a List and then find RestaurantOrderBook using category type. and put that List into a Map. it shows this error:


在封闭范围内定义的局部变量 itemList 必须是最终的或有效的最终

Local variable itemList defined in an enclosing scope must be final or effectively final



Query query = new Query();
String categ = category;
query.addCriteria(Criteria.where("restaurantId").is(restaurantId));

List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();
itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
System.out.println("size : " + itemList.size());
Map<String , List<RestaurantOrderBook>> map = new HashMap<String , List<RestaurantOrderBook>>();
        Arrays.asList("TakeAway", "Dining").forEach(e ->{

//Following line throws error:              
List<RestaurantOrderBook> list  = itemList.stream().filter(a -> !a.getOrderType().isEmpty() && a.getOrderType().equals(e)).collect(Collectors.toList());
                map.put(e, list);
        });

我还有另一种情况:

@Override
    public EventReportRewardsPoints eventReportRewardsPoints(String organizerId) {
        try{
            List<Event> listOfEvents = eventRepo.findByOrganizerId(organizerId);
            EventReportRewardsPoints eventTransReport = new EventReportRewardsPoints();
            Integer soldTics = 0;
            Double totalRevenue = 0d;
            Integer soldToday  = 0;

            Integer findTotalAvailableTics = 0;
            Integer findTotalQtytics = 0;

            for (Event event : listOfEvents) {
                List<EventTicket> eventTicket = eventTicketRepo.findByEventId(event.getId());

                Integer sumOfAvailabletics = eventTicket.stream()
                        .mapToInt(EventTicket::getRemainingTickets).sum();
                findTotalAvailableTics = findTotalAvailableTics + sumOfAvailabletics;

                Integer sumOfQtytics = eventTicket.stream().mapToInt(EventTicket::getQty).sum();
                findTotalQtytics  = findTotalQtytics + sumOfQtytics;

                List<EventTicketBook> listOfEventsTic = eventTicketBookRepository.findByEventId(event.getId());
                for (EventTicketBook eventTicketBook : listOfEventsTic) {
                    Double sumOfSales = eventTicketBook.getTickets().stream().mapToDouble(EventTicket::getPrice).sum();
                    totalRevenue = totalRevenue + sumOfSales;
                    Date now = new Date();
                    System.out.println("create date : " + eventTicketBook.getCreateOn());
                    /*if(now.compareTo(eventTicketBook.getCreateOn()) == 0){
                        Integer sumOfSoldToday = eventTicketBook.getTickets().stream().mapToInt(EventTicket::getQty).sum();
                        soldToday = soldToday + sumOfSoldToday;
                    }*/
                }
            }
            System.out.println("findTotalQtytics : " + findTotalQtytics);
            System.out.println("findTotalAvailableTics : " + findTotalAvailableTics);
            soldTics = findTotalQtytics - findTotalAvailableTics;
            eventTransReport.setTotalRevenue(totalRevenue);
            eventTransReport.setSoldToday(soldToday);
            eventTransReport.setTicketsSold(soldTics);
            return eventTransReport;
        }catch(Exception e ){
            e.printStackTrace();
        }
        return null;
    }

我如何使用lamda表达式来实现这个目标。??

How do i achive this using lamda expression.??

推荐答案

您在lambda表达式中使用 itemList 。因此它必须是最终的。

You are using itemList within a lambda expression. Therefore it has to be final.

Java 8引入了有效最终的新概念,这意味着,编译器会检查所使用的变量是否为最终使用而不是强迫开发人员明确声明它为最终版。

Java 8 introduces the new concept of effectivly final, which means, the compiler checks, if a used variable is final in usage and does not force the developer to explicitly declare it as final.

因此,如果您将代码更改为

So if you change your code to

final List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();

您将看到编译器在以下位置出现错误:

you will see, that the compiler gives you an error at:

itemList = mongoTemplate.find(query, RestaurantOrderBook.class);

因为您正在重新分配 itemList 。这就是为什么 itemList 也没有有效的最终结果。如果你将这两行压缩到

because you are reasigning itemList. That is why itemList is not effectivly final as well. If you squash these two lines to

List<RestaurantOrderBook> itemList = mongoTemplate.find(query, RestaurantOrderBook.class);

它应该有效。

这篇关于Java 8显示了此错误。在封闭范围内定义的局部变量itemList必须是最终的或有效的final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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