在开发中,经常会遇到需要多重循环封装值的情况,在一对多等情境下巧用Iterator的remove可以显著提高多重循环的效率。
例:多重目录,一级目录对应多个二级目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public List<FirstSubject> getSubjectList() { List<FirstSubject> list = new ArrayList<FirstSubject>(); QueryWrapper<Subject> firstSubjectWrapper = new QueryWrapper<>(); QueryWrapper<Subject> secondSubjectWrapper = new QueryWrapper<>(); firstSubjectWrapper.eq("parent_id","0"); secondSubjectWrapper.ne("parent_id","0"); List<Subject> firstList = baseMapper.selectList(firstSubjectWrapper); List<Subject> secondList = baseMapper.selectList(secondSubjectWrapper); for (int i = 0; i < firstList.size(); i++) { Subject subject = firstList.get(i); FirstSubject firstSubject = new FirstSubject(); BeanUtils.copyProperties(subject,firstSubject); List<SecondSubject> secondSubjectList = new ArrayList<>(); Iterator<Subject> iterator = secondList.iterator(); while(iterator.hasNext()){ Subject tempSubject = iterator.next(); if(tempSubject.getParentId().equals(subject.getId())) { SecondSubject secondSubject = new SecondSubject(); BeanUtils.copyProperties(tempSubject,secondSubject); secondSubjectList.add(secondSubject); iterator.remove(); } } firstSubject.setChildren(secondSubjectList); list.add(firstSubject); } return list; }
|
其中,内循环中使用iterator的remove删除了对应的二级目录,这样在之后的外循环中就不会在重复处理这个无效数据了(因为二级目录只对应一个一级目录)。