java.util.stream with ResultSet

The first thing you have to understand is that code like try (Connection connection = dataSource.getConnection()) { … try (PreparedStatement pSt = connection.prepareStatement(sql)) { … return stream; } } does not work as by the time you leave the try blocks, the resources are closed while the processing of the Stream hasn’t even started. The … Read more

Null safe Collection as Stream in Java 8

You could use Optional : Optional.ofNullable(collection).orElse(Collections.emptySet()).stream()… I chose Collections.emptySet() arbitrarily as the default value in case collection is null. This will result in the stream() method call producing an empty Stream if collection is null. Example : Collection<Integer> collection = Arrays.asList (1,2,3); System.out.println (Optional.ofNullable(collection).orElse(Collections.emptySet()).stream().count ()); collection = null; System.out.println (Optional.ofNullable(collection).orElse(Collections.emptySet()).stream().count ()); Output: 3 0 Alternately, … Read more

Is mapToDouble() really necessary for summing a List with Java 8 streams?

Is there some way to squeeze autoboxing in to make this shorter? Yes, there is. You can simply write: double sum = vals.stream().mapToDouble(d->d).sum(); This makes the unboxing implicit but, of course, does not add to efficiency. Since the List is boxed, unboxing is unavoidable. An alternative approach would be: double sum = vals.stream().reduce(0.0, Double::sum); It … Read more

Can I duplicate a Stream in Java 8?

It is not possible to duplicate a stream in this way. However, you can avoid the code duplication by moving the common part into a method or lambda expression. Supplier<IntStream> supplier = () -> IntStream.range(1, 100).filter(n -> n % 2 == 0); supplier.get().filter(…); supplier.get().filter(…);

Java 8 stream map on entry set

Simply translating the “old for loop way” into streams: private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) { int subLength = prefix.length(); return input.entrySet().stream() .collect(Collectors.toMap( entry -> entry.getKey().substring(subLength), entry -> AttributeType.GetByName(entry.getValue()))); }

Is there an elegant way to process a stream in chunks?

Elegance is in the eye of the beholder. If you don’t mind using a stateful function in groupingBy, you can do this: AtomicInteger counter = new AtomicInteger(); stream.collect(groupingBy(x->counter.getAndIncrement()/chunkSize)) .values() .forEach(database::flushChunk); This doesn’t win any performance or memory usage points over your original solution because it will still materialize the entire stream before doing anything. If … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)