foreach:对流的每个元素执行操作但不转换或返回数据的终端操作。
map:转换流中的每个元素并返回转换元素的新流。
带有列表的基本 foreach
import java.util.arrays; import java.util.list; public class foreachexample { public static void main(string[] args) { list<string> names = arrays.aslist("alice", "bob", "charlie"); // print each name using foreach names.foreach(name -> system.out.println(name)); } }
示例
List<String> names = Arrays.asList("Alice", "Bob"); names.stream().forEach(System.out::println); // Simply prints each name List<Integer> nameLengths = names.stream() .map(String::length) // Transforms each name to its length .collect(Collectors.toList());
以上就是流中的 forEach 和 map 有什么区别?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号