如何在Java8中使用foreach循环中的变量?

如何在Java8中使用foreach循环中的变量?,java,java-8,Java,Java 8,这是我实际的for-each循环。我需要将其转换为java8 for-loop for (PromotionEntity promotionEntity : pestudents) { List<ClassAttendanceChild> attendancelist = session.createQuery("from ClassAttendanceChild where attendanceadded='" + day + "' and pid.

这是我实际的for-each循环。我需要将其转换为java8 for-loop

for (PromotionEntity promotionEntity : pestudents) {
                List<ClassAttendanceChild> attendancelist = session.createQuery("from ClassAttendanceChild where attendanceadded='" + day + "' and pid.pId='" + promotionEntity.getpId() + "'").list();
                if (!attendancelist.isEmpty()) {
                    ClassAttendanceChild attendenceDetails = (ClassAttendanceChild) attendancelist.get(0);
                    if (attendenceDetails.getStatus().equalsIgnoreCase("yes")) {
                        present++;
                        System.out.println("present = " + present);
                    } else {
                        Absent++;
                        System.out.println("Absent = " + Absent);
                    }
                } else {
                    nottaken++;
                    System.out.println("nottaken = " + nottaken);
                }
            }
for(PromotionEntity PromotionEntity:pestudents){
List attendancelist=session.createQuery(“来自ClassAttendanceChild,其中AttendanceHeadded=”“+day+”,pid.pid=”“+promotionEntity.getpId()+”)”).List();
如果(!attendancelist.isEmpty()){
ClassAttendanceChild AttendanceDetails=(ClassAttendanceChild)attendancelist.get(0);
if(attendenceDetails.getStatus().equalsIgnoreCase(“是”)){
present++;
System.out.println(“present=”+present);
}否则{
缺席++;
System.out.println(“缺席=”+缺席);
}
}否则{
nottake++;
System.out.println(“nottake=“+nottake”);
}
}
如何将其转换为java8 for循环,在该变量增量中会出现异常:

 pestudents.forEach(promotionEntity -> {
            List<ClassAttendanceChild> attendancelist = session.createQuery("from ClassAttendanceChild where attendanceadded='" + day + "' and pid.pId='" + promotionEntity.getpId() + "'").list();
            if (!attendancelist.isEmpty()) {
                 ClassAttendanceChild attendenceDetails = (ClassAttendanceChild) attendancelist.get(0);
                  if (attendenceDetails.getStatus().equalsIgnoreCase("yes")) {
//                    present++;
//                    System.out.println("present = " + present);
                } else {
//                    Absent++;
//                    System.out.println("Absent = " + Absent);
                }
            } else {
//                nottaken++;
//                System.out.println("nottaken = " + nottaken);
            }


        });
pestudents.forEach(促销实体->{
List attendancelist=session.createQuery(“来自ClassAttendanceChild,其中AttendanceHeadded=”“+day+”,pid.pid=”“+promotionEntity.getpId()+”)”).List();
如果(!attendancelist.isEmpty()){
ClassAttendanceChild AttendanceDetails=(ClassAttendanceChild)attendancelist.get(0);
if(attendenceDetails.getStatus().equalsIgnoreCase(“是”)){
//present++;
//System.out.println(“present=”+present);
}否则{
//缺席++;
//System.out.println(“缺席=”+缺席);
}
}否则{
//nottake++;
//System.out.println(“nottake=“+nottake”);
}
});

不允许修改在传递给
forEach
的方法之外定义的局部变量。它们必须声明为
final
,或者至少是有效的final,这意味着它们在初始化后永远不会更改

您可以做的是将
present
和其他局部变量更改为允许您修改的实例变量或类变量


也就是说,我建议您保留旧语法,它更适合您尝试执行的操作。

不允许您修改传递给
forEach
的方法之外定义的局部变量。它们必须声明为
final
,或者至少是有效的final,这意味着它们在初始化后永远不会更改

您可以做的是将
present
和其他局部变量更改为允许您修改的实例变量或类变量


也就是说,我建议您保留旧语法,它更适合您尝试执行的操作。

要并行化此代码,您可以使用AtomicInteger作为线程安全计数器

AtomicInteger present = new AtomicInteger();
AtomicInteger absent = new AtomicInteger();
AtomicInteger nottaken = new AtomicInteger();

pestudents.parallelStream().forEach(promotionEntity -> {
        List<ClassAttendanceChild> attendancelist = session.createQuery("from ClassAttendanceChild where attendanceadded='" + day + "' and pid.pId='" + promotionEntity.getpId() + "'").list();
        if (!attendancelist.isEmpty()) {
             ClassAttendanceChild attendenceDetails = (ClassAttendanceChild) attendancelist.get(0);
              if (attendenceDetails.getStatus().equalsIgnoreCase("yes")) {
                  present.incrementAndGet();
                  System.out.println("present = " + present);
            } else {
                  absent.incrementAndGet();
                  System.out.println("Absent = " + Absent);
            }
        } else {
              nottaken.incrementAndGet();
              System.out.println("nottaken = " + nottaken);
        }
    });
AtomicInteger present=新的AtomicInteger();
AtomicInteger缺席=新的AtomicInteger();
AtomicInteger nottake=新的AtomicInteger();
pestudents.parallelStream().forEach(promotionEntity->{
List attendancelist=session.createQuery(“来自ClassAttendanceChild,其中AttendanceHeadded=”“+day+”,pid.pid=”“+promotionEntity.getpId()+”)”).List();
如果(!attendancelist.isEmpty()){
ClassAttendanceChild AttendanceDetails=(ClassAttendanceChild)attendancelist.get(0);
if(attendenceDetails.getStatus().equalsIgnoreCase(“是”)){
present.incrementAndGet();
System.out.println(“present=”+present);
}否则{
不存在。incrementAndGet();
System.out.println(“缺席=”+缺席);
}
}否则{
nottake.incrementAndGet();
System.out.println(“nottake=“+nottake”);
}
});

要并行化此代码,可以使用AtomicInteger作为线程安全计数器

AtomicInteger present = new AtomicInteger();
AtomicInteger absent = new AtomicInteger();
AtomicInteger nottaken = new AtomicInteger();

pestudents.parallelStream().forEach(promotionEntity -> {
        List<ClassAttendanceChild> attendancelist = session.createQuery("from ClassAttendanceChild where attendanceadded='" + day + "' and pid.pId='" + promotionEntity.getpId() + "'").list();
        if (!attendancelist.isEmpty()) {
             ClassAttendanceChild attendenceDetails = (ClassAttendanceChild) attendancelist.get(0);
              if (attendenceDetails.getStatus().equalsIgnoreCase("yes")) {
                  present.incrementAndGet();
                  System.out.println("present = " + present);
            } else {
                  absent.incrementAndGet();
                  System.out.println("Absent = " + Absent);
            }
        } else {
              nottaken.incrementAndGet();
              System.out.println("nottaken = " + nottaken);
        }
    });
AtomicInteger present=新的AtomicInteger();
AtomicInteger缺席=新的AtomicInteger();
AtomicInteger nottake=新的AtomicInteger();
pestudents.parallelStream().forEach(promotionEntity->{
List attendancelist=session.createQuery(“来自ClassAttendanceChild,其中AttendanceHeadded=”“+day+”,pid.pid=”“+promotionEntity.getpId()+”)”).List();
如果(!attendancelist.isEmpty()){
ClassAttendanceChild AttendanceDetails=(ClassAttendanceChild)attendancelist.get(0);
if(attendenceDetails.getStatus().equalsIgnoreCase(“是”)){
present.incrementAndGet();
System.out.println(“present=”+present);
}否则{
不存在。incrementAndGet();
System.out.println(“缺席=”+缺席);
}
}否则{
nottake.incrementAndGet();
System.out.println(“nottake=“+nottake”);
}
});

与往常一样,当您决定开始运行时,您必须返回到更高级别的目标描述,然后以FP风格重写代码

您需要确定三类事件的总数:“出席”、“缺席”和“未参加”。以下是关于如何通过FP方式实现它的建议(感谢Stuart Marks指出如何构建库提供的频率计数采集器):


和往常一样,当您决定使用功能性代码时,必须返回到更高级别的目标描述,然后以FP风格重写代码

您需要确定三类事件的总数:“出席”、“缺席”和“未参加”。以下是关于如何通过FP方式实现的建议(感谢Stuart Marks指出如何
public static void main(String[] args) {
  final List<PromotionEntity> pestudents = ...your initialization...
  final Map<String, Integer> freqs = pestudents.stream().map(pe -> {
    final List<ClassAttendanceChild> attendancelist = session.createQuery(
           "from ClassAttendanceChild where attendanceadded='" + day + 
           "' and pid.pId='" + promotionEntity.getpId() + "'")
      .list();
    return attendancelist.isEmpty()? "nottaken" 
        : attendancelist.get(0).getStatus().equalsIgnoreCase("yes")?
            "present" : "absent";
  }).collect(toFrequencyMap());
  System.out.println(freqs);
}

static Integer zeroForNull(Integer i) { return i == null? 0 : i; }

static <K> Collector<K, Map<K, Integer>, Map<K, Integer>> toFrequencyMap() {
  return Collector.of(
      HashMap<K, Integer>::new,
      (acc, key) -> acc.compute(key, (x, count) -> zeroForNull(count) + 1),
      (acc, source) -> {
        source.forEach((key, sourceCount) ->
          acc.compute(key, (x,accCount) ->
            sourceCount + zeroForNull(accCount)));
        return acc;
      },
      Collector.Characteristics.UNORDERED);
}