Auto indexing improved for() loops
Anatoly Kupriyanov
kan.izh at gmail.com
Thu Dec 7 21:05:56 UTC 2023
>
> Unfortunately, Record Patterns in enhanced for loops have been removed by JEP
> 440 <https://openjdk.org/jeps/440> in Java 21. With enabled preview
> features, you were able to write the following in Java 20:
>
> String[] strings = getSomeStrings();
> for (ListIndex(int index, String element) : enumerate(strings)) {
> System.out.println(index + ": " + element);
> }
>
> To be fair it looks ugly, especially the fact that you need to specify
exact types. I would expect use of "var", at least for the element type.
Technically it could be implemented easily as an extension for streams-api,
no changes in the language required.
Stream.of(strings).forEachIndexed((index, element) -> {//BiFunction
System.out.println(index + ": " + element);
});
Or even make stream modifier to have allow proper chaining:
Stream.of(strings)
.indexed()
.filter(i -> i.index() % 3 == 0 && !i.element().isEmpty())
.forEach(i -> {
System.out.println(i.index() + ": " + i.element());
});
This thing could also be parallelStream()
--
WBR, Anatoly.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231207/67fe9729/attachment.htm>
More information about the amber-dev
mailing list