java-stream

How to apply multiple Filters on Java Stream?

萝らか妹 提交于 2019-12-05 00:54:55
I have to filter a Collection of Objects by a Map, which holds key value pairs of the Objects field names and field values. I am trying to apply all filters by stream().filter(). The Objects are actually JSON, therefore the Map holds the names of its variables as well as the value they have to contain in order to be accepted, but for simplicity reasons and because its not relevant to the question I wrote a simple Testclass for simulating the behaviour: public class TestObject { private int property1; private int property2; private int property3; public TestObject(int property1, int property2,

Determine if a list composed of anagram elements in Java 8

和自甴很熟 提交于 2019-12-05 00:46:05
I want to determine if a list is anagram or not using Java 8. Example input: "cat", "cta", "act", "atc", "tac", "tca" I have written the following function that does the job but I am wondering if there is a better and elegant way to do this. boolean isAnagram(String[] list) { long count = Stream.of(list) .map(String::toCharArray) .map(arr -> { Arrays.sort(arr); return arr; }) .map(String::valueOf) .distinct() .count(); return count == 1; } It seems I can't sort char array with Stream.sorted() method so that's why I used a second map operator. If there is some way that I can operate directly on

Sort Map<String, Long> by value reversed

元气小坏坏 提交于 2019-12-05 00:39:22
问题 I have a Map<String, Long> map which I want to sort by the Long value in reversed order using the features of Java 8. With Google I found this thread which provides this solution Map<String, Long> sortedMap = map.entrySet().stream() .sorted(comparing(Entry::getValue)) .collect(toMap(Entry::getKey, Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new)); If I want to have the order reversed in the comments it says to use comparing(Entry::getValue).reversed() instead of comparing(Entry::getValue)

Cannot make filter->forEach->collect in one stream?

非 Y 不嫁゛ 提交于 2019-12-05 00:38:24
I want to achieve something like this: items.stream() .filter(s-> s.contains("B")) .forEach(s-> s.setState("ok")) .collect(Collectors.toList()); filter, then change a property from the filtered result, then collect the result to a list. However, the debugger says: Cannot invoke collect(Collectors.toList()) on the primitive type void . Do I need 2 streams for that? The forEach is designed to be a terminal operation and yes - you can't do anything after you call it. The idiomatic way would be to apply a transformation first and then collect() everything to the desired data structure. The

Must partitioningBy produce a map with entries for true and false?

匆匆过客 提交于 2019-12-05 00:26:04
The partitioningBy collector applies a predicate to each element in a stream and produces a map from booleans to lists of elements from the stream that satisfied or didn't satisfy the predicate. For instance: Stream.of(1,2,3,4).collect(partitioningBy(x -> x >= 3)) // {false=[1, 2], true=[3, 4]} As discussed in What's the purpose of partitioningBy , the observed behavior is that partitioningBy always returns a map with entries for both true and false . E.g.: Stream.empty().collect(partitioningBy(x -> false)); // {false=[], true=[]} Stream.of(1,2,3).collect(partitioningBy(x -> false)); // {false

Java Streams: get values grouped by inner map key

岁酱吖の 提交于 2019-12-04 23:27:50
I have Map<A, Map<B, C>> and I want to get Map<B, List<C>> from it using Java Streams. I try to do it as follows: public <A, B, C> Map<B, List<C>> groupsByInnerKey(Map<A, Map<B, C>> input) { return input.values() .stream() .flatMap(it -> it.entrySet().stream()) .collect(Collectors.groupingBy(Map.Entry::getKey)); } What I expect: flatMap gives a Stream of Map.Entry<B, C> collect(Collectors.groupingBy(...)) takes function which is applied to Map.Entry<B, C> and returns B , thus it collects values of C into List<C> . But it doesn't compile, literally: Non-static method cannot be referenced from a

Java 8 stream - sum of objects

◇◆丶佛笑我妖孽 提交于 2019-12-04 22:39:45
Let's say I have a list of objects implementing below interface: public interface Summable<T> { T add(T o1); } Let's say I have also some class which is able to sum these objects: public class Calculator<T extends Summable<T>> { public T sum(final List<T> objects) { if (null == objects) { throw new IllegalArgumentException("Ups, list of objects cannot be null!"); } T resultObject = null; for (T object : objects) { resultObject = object.add(resultObject); } return resultObject; } } How can I achieve the same using Java 8 streams? I'm playing around a custom Collector, but couldn't figure out

How can I create a Stream<String[]> with only one element with Stream.of?

為{幸葍}努か 提交于 2019-12-04 22:30:23
Using Stream.of to create generic streams is very convenient, but what if I want to create a Stream<String[]> of only one element? Let’s say I have: String[] tropicalFruits = new String[] {"pineapple", "banana", "mango"}; String[] fruits = new String[] {"melon", "peach", "apple"}; Then Stream.of(tropicalFruits, fruits) produces a Stream<String[]> of two elements. How can I achieve the same for a stream of a single element? If I try: Stream<String[]> fruityStream = Stream.of(tropicalFruits); I get: Error: incompatible types: inference variable T has incompatible bounds equality constraints:

How to stream a map with collection using Java 8 streams?

微笑、不失礼 提交于 2019-12-04 22:10:18
I'd like to stream a map with collection using Java 8 streams. For example, having the following data: Map<String, Collection<Integer>> data; I'd like to go over the elements handling each integer value with the corresponding key strings. For example: data.keyValueStream((k,v)-> ...) Any idea how to achieve this? Thanks. * Regarding the question "Why do you need it?", it could be a bunch of reasons and I'm not sure it's important. Anyhow, I'll "flow" with you... My specific scenario is to batch insert into a DB all the values, under their specific key. Let's keep it a general Java 8 stream

Sort the outer map by the value of the nested map

倾然丶 夕夏残阳落幕 提交于 2019-12-04 22:05:58
Sorting the outer map Map<String, Map<String, List<Integer>>> by the list size in the nested map retaining the outer and inner keys as before. You may solve this by generalizing the process: private static <K,V,R> Map<K,R> replaceAndSortValues(Map<K,V> m, Function<V,R> f, Comparator<R> c) { return m.entrySet().stream() .map(e -> Map.entry(e.getKey(), f.apply(e.getValue()))) .sorted(Map.Entry.comparingByValue(c.reversed())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,b) -> { throw new AssertionError(); }, LinkedHashMap::new)); } This method creates a new map with the