我有一个 我需要按照下面的迭代逻辑找到给定元素的总和。例如,第一个外部迭代像640 + 480,然后是640 + 480 + 520,依此类推直到60。List<Integer> list=Arrays.asList(640,480,520,170,320,140,60);下一次迭代从 480+520 开始,然后是 480+520+170,依此类推。示例 Java 7 程序是这样的List<Integer> list=Arrays.asList(640,480,520,170,320,140,60); List<Integer> newListWithSum=new ArrayList<>(); for(int mainIndex=0;mainIndex<list.size();mainIndex++) { for(int index=mainIndex;index<list.size();index++) { int sum=0; for(int nestedIndex=mainIndex;nestedIndex<index+1;nestedIndex++) { sum=sum+list.get(nestedIndex); } newListWithSum.add(sum); } }但是我需要将上述逻辑更改为Java 8版本。请帮助/分享提示,按照下面的迭代编写一个简化的Java 8逻辑来求和
2 回答
白板的微信
TA贡献1883条经验 获得超3个赞
我觉得这和算法更相似,让我们一步一步来
1) 首先通过排除每次迭代中的第一个整数来获取所有子列表
List<Integer> list=Arrays.asList(640,480,520,170,320,140,60); List<List<Integer>> re = IntStream.range(0, list.size()) .mapToObj(sb->list.subList(sb, list.size())) .filter(s->s.size()>1) .collect(Collectors.toList()); re.forEach(ls->System.out.println(ls));
输出
[640, 480, 520, 170, 320, 140, 60] [480, 520, 170, 320, 140, 60] [520, 170, 320, 140, 60] [170, 320, 140, 60] [320, 140, 60] [140, 60]
2)现在在每个列表上进行求和
List<List<Integer>> re1 = re.stream() .map(j->IntStream.rangeClosed(2, j.size()).mapToObj(sl->j.stream().limit(sl).mapToInt(Integer::intValue).sum()).collect(Collectors.toList())) .collect(Collectors.toList()); re1.forEach(ls->System.out.println(ls));
输出
[1120, 1640, 1810, 2130, 2270, 2330] [1000, 1170, 1490, 1630, 1690] [690, 1010, 1150, 1210] [490, 630, 690] [460, 520] [200]
步骤 1 和步骤 2 的组合解决方案
List<List<Integer>> re = IntStream.range(0, list.size()) .mapToObj(sb->list.subList(sb, list.size())) .filter(s->s.size()>1) .map(j->IntStream.rangeClosed(2, j.size()).mapToObj(sl->j.stream().limit(sl).mapToInt(Integer::intValue).sum()).collect(Collectors.toList())) .collect(Collectors.toList());
守着一只汪
TA贡献1872条经验 获得超4个赞
如果您只想转换您拥有的代码,则可以使用以下代码段:
List<Integer> result = IntStream.range(0, list.size()) .mapToObj(i -> list.subList(i, list.size())) .flatMap(l -> IntStream.rangeClosed(1, l.size()).mapToObj(i -> l.subList(0, i).stream().reduce(0, Integer::sum))) .collect(Collectors.toList());
这将创建一个 from to 并映射应对项目进行汇总的所有列表。这些列表将再次映射到实际项目以计算总和。这在步骤中处于打开状态。最后,所有流都将平展到结果列表中的 finaly:Intstream0n - 1reduce
[640, 1120, 1640, 1810, 2130, 2270, 2330, 480, 1000, 1170, 1490, 1630, 1690, 520, 690, 1010, 1150, 1210, 170, 490, 630, 690, 320, 460, 520, 140, 200, 60]
添加回答
举报
0/150
提交
取消
