Posts

Showing posts with the label Java 8

Can You Split A Stream Into Two Streams?

Answer : A collector can be used for this. For two categories, use Collectors.partitioningBy() factory. This will create a Map from Boolean to List , and put items in one or the other list based on a Predicate . Note: Since the stream needs to be consumed whole, this can't work on infinite streams. And because the stream is consumed anyway, this method simply puts them in Lists instead of making a new stream-with-memory. You can always stream those lists if you require streams as output. Also, no need for the iterator, not even in the heads-only example you provided. Binary splitting looks like this: Random r = new Random(); Map<Boolean, List<String>> groups = stream .collect(Collectors.partitioningBy(x -> r.nextBoolean())); System.out.println(groups.get(false).size()); System.out.println(groups.get(true).size()); For more categories, use a Collectors.groupingBy() factory. Map<Object, List<String>> groups = stream ...

Convert ZonedDateTime To LocalDateTime At Time Zone

Answer : How can I convert it to LocalDateTime at time zone of Switzerland? You can convert the UTC ZonedDateTime into a ZonedDateTime with the time zone of Switzerland, but maintaining the same instant in time, and then get the LocalDateTime out of that, if you need to. I'd be tempted to keep it as a ZonedDateTime unless you need it as a LocalDateTime for some other reason though. ZonedDateTime utcZoned = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC); ZoneId swissZone = ZoneId.of("Europe/Zurich"); ZonedDateTime swissZoned = utcZoned.withZoneSameInstant(swissZone); LocalDateTime swissLocal = swissZoned.toLocalDateTime(); It helps to understand the difference between LocalDateTime and ZonedDateTime. What you really want is a ZonedDateTime . If you wanted to remove the timezone from the string representation, you would convert it to a LocalDateTime . What you're looking for is: ZonedDateTime swissZonedDateTime = withZoneSameInstant(ZoneId.of...