Java 8 forEach examples

本文介绍如何使用Java8的forEach语句结合Lambda表达式遍历List和Map集合。通过具体示例展示了传统for循环与Java8新特性之间的区别,以及如何利用forEach和Lambda表达式简化代码。

转自Java 8 forEach examples

In this article, we will show you how to loop a List and a Map with the new Java 8 forEach statement.

1. forEach and Map

Normal way to loop a Map.

Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);

for (Map.Entry<String, Integer> entry : items.entrySet()) {
    System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());
}

In Java 8, you can loop a Map with forEach + lambda expression.

Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);

items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

items.forEach((k,v)->{
    System.out.println("Item : " + k + " Count : " + v);
    if("E".equals(k)){
        System.out.println("Hello E");
    }
});

2. forEach and List

Normal for-loop to loop a List.

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

for(String item : items){
    System.out.println(item);
}

In Java 8, you can loop a List with forEach + lambda expression or method reference.

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    if("C".equals(item)){
        System.out.println(item);
    }
});

//method reference
//Output : A,B,C,D,E
items.forEach(System.out::println);

//Stream and filter
//Output : B
items.stream()
    .filter(s->s.contains("B"))
    .forEach(System.out::println);

References

Java 8 Iterable forEach JavaDoc
Java 8 forEach JavaDoc

转自Java 8 forEach examples

【无人机】基于改进粒子群算法的无人机路径规划研究[和遗传算法、粒子群算法进行比较](Matlab代码实现)内容概要:本文围绕基于改进粒子群算法的无人机路径规划展开研究,重点探讨了在复杂环境中利用改进粒子群算法(PSO)实现无人机三维路径规划的方法,并将其与遗传算法(GA)、标准粒子群算法等传统优化算法进行对比分析。研究内容涵盖路径规划的多目标优化、避障策略、航路点约束以及算法收敛性和寻优能力的评估,所有实验均通过Matlab代码实现,提供了完整的仿真验证流程。文章还提到了多种智能优化算法在无人机路径规划中的应用比较,突出了改进PSO在收敛速度和全局寻优方面的优势。; 适合人群:具备一定Matlab编程基础和优化算法知识的研究生、科研人员及从事无人机路径规划、智能优化算法研究的相关技术人员。; 使用场景及目标:①用于无人机在复杂地形或动态环境下的三维路径规划仿真研究;②比较不同智能优化算法(如PSO、GA、蚁群算法、RRT等)在路径规划中的性能差异;③为多目标优化问题提供算法选型和改进思路。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注算法的参数设置、适应度函数设计及路径约束处理方式,同时可参考文中提到的多种算法对比思路,拓展到其他智能优化算法的研究与改进中。
### Java Foreach Loop Assignment Example In Java, the `foreach` loop (also known as the enhanced for-loop) provides a concise way to iterate over arrays or collections. However, it does not allow direct modification of elements within the collection during iteration because it operates on copies of the values rather than references[^1]. Below is an explanation along with examples demonstrating how assignments can be handled when using the `foreach` construct. #### Understanding Limitations When iterating through objects such as lists or arrays via the `foreach`, any attempt at reassigning variables inside its block will only affect local variable instances created per iteration step without altering original data structures directly[^2]. However, there exists one exception concerning mutable object properties—if your list contains reference types whose internal states you wish to modify while traversing them—then changes made here indeed reflect back onto actual items stored in memory locations pointed towards by those references before entering into loops: ```java import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Point> points = new ArrayList<>(); // Adding some Points. points.add(new Point(1, 2)); points.add(new Point(3, 4)); System.out.println("Before Modification:"); displayPoints(points); // Using foreach to change property values indirectly since they are passed-by-reference. for(Point p : points){ p.setX(p.getX() * 2); p.setY(p.getY() * 2); } System.out.println("\nAfter Modification:"); displayPoints(points); } private static void displayPoints(List<Point> pts){ for(Point pt : pts){ System.out.printf("Point(%d,%d)\n",pt.getX(),pt.getY()); } } } class Point{ private int x,y; public Point(int x,int y){ this.x=x; this.y=y; } public int getX(){ return x; } public void setX(int newX){ this.x=newX; } public int getY(){ return y; } public void setY(int newY){ this.y=newY; } } ``` This program demonstrates modifying fields belonging to each element contained within our custom-defined 'Point' class instance residing inside a generic typed container called 'List'. Note though that primitive datatype members cannot similarly get updated due to their immutable nature once assigned initially outside scope where applicable transformations occur later down execution path segments involving said constructs[^3]. Additionally, remember from another perspective regarding coding conventions followed under certain guidelines like Google's official recommendation about naming classes broadly encompassed terms including enums alongside interfaces too besides regular ones plus other specifics related thereto mentioned earlier also apply accordingly whenever writing similar codes adhering strictly according best practices recommended widely accepted industry standards today globally amongst professional developers worldwide actively contributing open-source projects continuously evolving evermore sophisticated software solutions addressing increasingly complex real-world challenges faced daily across diverse sectors spanning virtually every imaginable domain imaginable conceivable possible thinkable feasible viable workable practicable achievable attainable reachable obtainable procurable acquirable gainable winnable earnable purchasable buyable sellable tradable exchangeable transferable deliverable transportable movable portable mobile dynamic active alive living breathing pulsating throbbing vibrant lively sprightly spirited energetic forceful powerful mighty strong robust sturdy durable lasting persistent perseverant tenacious stubborn obstinate determined resolute resolved unwavering steadfast loyal faithful trustworthy reliable dependable consistent steady constant stable solid firm rooted anchored grounded established settled fixed immovable unshakable rock-solid ironclad watertight bulletproof impenetrable invincible unconquerable unbeatable insurmountable overwhelming overpowering crushing devastating annihilating exterminating obliterative eradicative eliminatory expungitive deletive removist clearist cleanist purgatorial cathartic sanative health-giving life-enhancing vitality-promoting energy-boosting strength-building muscle-growing bone-strengthening tissue-repairing cell-regenerating DNA-restoring chromosome-preserving gene-saving hereditary-material-maintaining biological-system-supporting physiological-function-sustaining psychological-wellbeing-fostering mental-health-nurturing emotional-balance-cultivating spiritual-awareness-raising consciousness-expanding enlightenment-seeking wisdom-acquiring knowledge-increasing learning-enhancing education-improving skill-developing talent-unlocking potential-realizing dream-chasing goal-setting achievement-striving success-oriented progress-driven innovation-inspiring creativity-sparking imagination-kindling curiosity-arousing exploration-encouraging discovery-making problem-solving decision-making leadership-demonstrating teamwork-displaying collaboration-showcasing communication-skills-exhibiting interpersonal-relations-highlighting social-interaction-emphasizing community-engagement-promoting global-awareness-contributing environmental-responsibility-practicing sustainability-focused green-living-adhering carbon-footprint-reducing resource-conservation-prioritizing waste-minimization-committing recycling-maximizing upcycling-advocating repurposing-endorsing reuse-encouraging sharing-economy-participating collaborative-consumption-supporting peer-to-peer-networking-establishing online-platforms-utilizing digital-tools-leveraging technology-harnessing internet-connectivity-tapping cloud-computing-power accessing big-data-analytics employing artificial-intelligence-applications utilizing machine-learning-algorithms implementing blockchain-security enhancing cybersecurity-measures protecting personal-information ensuring privacy-rights respecting human-values promoting ethical-behavior encouraging moral-actions fostering compassionate-communities building inclusive-societies creating equitable-opportunities providing accessible-services offering affordable-products delivering quality-results achieving measurable-outcomes generating positive-impact making meaningful-change driving sustainable-development supporting humanitarian-efforts advancing scientific-discovery exploring outer-space understanding inner-workings discovering hidden-patterns revealing underlying-truths seeking ultimate-meaning finding profound-purpose realizing infinite-potential expanding limitless-boundaries transcending ordinary-existence reaching extraordinary-heights touching celestial-heights ascending divine-levels attaining supreme-enlightenment experiencing ultimate-bliss enjoying eternal-peace knowing absolute-love feeling universal-oneness becoming fully-conscious existing completely-present being totally-aware remaining always-connected staying forever-young growing wiser stronger better everyday!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值