Java Streams: Accessing Element Index with .map() | Indexed Transformations
The ".map" function in Java streams is used to transform each element in a stream into a new element based on a given function. The "map" function takes a lambda expression or method reference as an argument, which defines the transformation logic.\n\nThe "map" function does not have a built-in index parameter. If you need to access the index of each element in the stream while mapping, you can use the "IntStream.range" method to generate a stream of indices and then use the "mapToObj" function to convert each index to its corresponding element in the original stream.\n\nHere is an example of using ".map" with indices in Java streams:\n\njava\nList<String> names = Arrays.asList(\"John\", \"Alice\", \"Bob\");\n\nList<String> indexedNames = IntStream.range(0, names.size())\n .mapToObj(index -> index + \": \" + names.get(index))\n .collect(Collectors.toList());\n\nSystem.out.println(indexedNames);\n\n\nOutput:\n\n[0: John, 1: Alice, 2: Bob]\n\n\nIn this example, the ".mapToObj" function is used to transform each index into a string with the corresponding name from the original list. The resulting stream of indexed names is then collected into a new list.
原文地址: https://www.cveoy.top/t/topic/p95d 著作权归作者所有。请勿转载和采集!