Java 8 apply function to all elements of Stream without breaking stream chain

There are (at least) 3 ways. For the sake of example code, I’ve assumed you want to call 2 consumer methods methodA and methodB: A. Use peek(): list.stream().peek(x -> methodA(x)).forEach(x -> methodB(x)); Although the docs say only use it for “debug”, it works (and it’s in production right now) B. Use map() to call methodA, … Read more

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g. animalMap.entrySet().stream() .forEach( pair -> { if (pair.getValue() != null) { myMap.put(pair.getKey(), pair.getValue()); } else { myList.add(pair.getKey()); } } ); Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code. Update: using Map.forEach makes the code … Read more

Can Java 8 Streams operate on an item in a collection, and then remove it?

You can do it like this: set.removeIf(item -> { if (!item.qualify()) return false; item.operate(); return true; }); If item.operate() always returns true you can do it very succinctly. set.removeIf(item -> item.qualify() && item.operate()); However, I don’t like these approaches as it is not immediately clear what is going on. Personally, I would continue to use … Read more

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don’t have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort. And you want to get the keys; use map to transform entries to keys. List<Type> types = countByType.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getValue)) .map(Map.Entry::getKey) .collect(Collectors.toList());

Word frequency count Java 8

I want to share the solution I found because at first I expected to use map-and-reduce methods, but it was a bit different. Map<String,Long> collect = wordsList.stream() .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() )); Or for Integer values: Map<String,Integer> collect = wordsList.stream() .collect( Collectors.groupingBy( Function.identity(), Collectors.summingInt(e -> 1) )); EDIT I add how to sort the map … Read more

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