I have the following code that iterates over Java DateTimeFormatter
pattern combinations of "E".."EEEE"
and "M".."MMMM"
.
My question is, is there an idiomatic (or just 'more idiomatic') way to use Java Streams in this case?
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class DateTimeFormattingStackOverflow {
static LocalDateTime dateTime = LocalDateTime.now();
static Stream<String> substrings(String str) {
return IntStream.range(1, str.length() + 1)
.mapToObj(i -> str.substring(0, i));
}
static void printDateTime(String pattern) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
System.out.println(pattern + ", " + dtf.format(dateTime));
}
public static void main(String[] args) {
Stream<String> patterns = substrings("EEEE")
.flatMap(e -> substrings("MMMM").map(m -> e + " " + m))
.map(em -> em + " d");
patterns.forEach(DateTimeFormattingStackOverflow::printDateTime);
}
}
Output
E M d, Sat 7 1
E MM d, Sat 07 1
E MMM d, Sat Jul 1
E MMMM d, Sat July 1
EE M d, Sat 7 1
EE MM d, Sat 07 1
EE MMM d, Sat Jul 1
EE MMMM d, Sat July 1
...