Fetch first element of stream matching the criteria

This might be what you are looking for: yourStream .filter(/* your criteria */) .findFirst() .get(); And better, if there’s a possibility of matching no element, in which case get() will throw a NPE. So use: yourStream .filter(/* your criteria */) .findFirst() .orElse(null); /* You could also create a default object here */ An example: public … Read more

In Java 8 how do I transform a Map to another Map using a lambda?

You could use a Collector: import java.util.*; import java.util.stream.Collectors; public class Defensive { public static void main(String[] args) { Map<String, Column> original = new HashMap<>(); original.put(“foo”, new Column()); original.put(“bar”, new Column()); Map<String, Column> copy = original.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> new Column(e.getValue()))); System.out.println(original); System.out.println(copy); } static class Column { public Column() {} public Column(Column c) … Read more

Can you split a stream into two streams?

A collector can be used for this. For two categories, use Collectors.partitioningBy() factory. This will create a Map<Boolean, 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 … Read more

In Java, what are the advantages of streams over loops? [closed]

Interesting that the interview question asks about the advantages, without asking about disadvantages, for there are are both. Streams are a more declarative style. Or a more expressive style. It may be considered better to declare your intent in code, than to describe how it’s done: return people .filter( p -> p.age() < 19) .collect(toList()); … Read more

Is it possible to cast a Stream in Java 8?

I don’t think there is a way to do that out-of-the-box. A possibly cleaner solution would be: Stream.of(objects) .filter(c -> c instanceof Client) .map(c -> (Client) c) .map(Client::getID) .forEach(System.out::println); or, as suggested in the comments, you could use the cast method – the former may be easier to read though: Stream.of(objects) .filter(Client.class::isInstance) .map(Client.class::cast) .map(Client::getID) .forEach(System.out::println);

Why is a combiner needed for reduce method that converts type in java 8

Eran’s answer described the differences between the two-arg and three-arg versions of reduce in that the former reduces Stream<T> to T whereas the latter reduces Stream<T> to U. However, it didn’t actually explain the need for the additional combiner function when reducing Stream<T> to U. One of the design principles of the Streams API is … Read more

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