collectors

How to apply Filtering on groupBy in java streams

谁都会走 提交于 2019-11-27 20:54:04
问题 How do you group first and then apply filtering using Java streams? Example : Consider this Employee class: I want to group by Department with a list of an employee having a salary greater than 2000. public class Employee { private String department; private Integer salary; private String name; //getter and setter public Employee(String department, Integer salary, String name) { this.department = department; this.salary = salary; this.name = name; } } This is how I can do this List<Employee>

Java 8 Collectors.toMap SortedMap

有些话、适合烂在心里 提交于 2019-11-27 18:05:12
I'm using Java 8 lambdas and want to use Collectors toMap to return a SortedMap . The best I can come up with is to call the following Collectors toMap method with a dummy mergeFunction and mapSupplier equal to TreeMap::new . public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier) { BiConsumer<M, T> accumulator = (map, element) -> map.merge(keyMapper.apply(element), valueMapper.apply(element), mergeFunction); return new CollectorImpl<

How to add elements of a Java8 stream into an existing List

六眼飞鱼酱① 提交于 2019-11-27 17:07:16
Javadoc of Collector shows how to collect elements of a stream into a new List. Is there an one-liner that adds the results into an existing ArrayList? Stuart Marks NOTE: nosid's answer shows how to add to an existing collection using forEachOrdered() . This is a useful and effective technique for mutating existing collections. My answer addresses why you shouldn't use a Collector to mutate an existing collection. The short answer is no , at least, not in general, you shouldn't use a Collector to modify an existing collection. The reason is that collectors are designed to support parallelism,

Java lang IllegalAccess on collecting Guava Immutable Table via HashBasedTable accumulator

限于喜欢 提交于 2019-11-27 15:53:50
Error while executing below code, Caused by: java.lang.IllegalAccessError: tried to access class com.google.common.collect.AbstractTable from class ImmutableTable.copyOf(listItemsToProcess.parallelStream() .map(item -> ProcessorInstanceProvider.getInstance() .buildImmutableTable(item)) .collect(() -> HashBasedTable.create(), HashBasedTable::putAll, HashBasedTable<Integer, String, Boolean>::putAll) ); Error in coming on - HashBasedTable::putAll Using Oracle's 1.8 jre This is a compiler bug, related reports are JDK-8152643 : “Javac compiles method reference that allows results in an

What's the purpose of partitioningBy

情到浓时终转凉″ 提交于 2019-11-27 14:17:53
For example, if I intend to partition some elements, I could do something like: Stream.of("I", "Love", "Stack Overflow") .collect(Collectors.partitioningBy(s -> s.length() > 3)) .forEach((k, v) -> System.out.println(k + " => " + v)); which outputs: false => [I] true => [Love, Stack Overflow] But for me partioningBy is only a subcase of groupingBy . Although the former accepts a Predicate as parameter while the latter a Function , I just see a partition as a normal grouping function. So the same code does exactly the same thing: Stream.of("I", "Love", "Stack Overflow") .collect(Collectors

What kind of List<E> does Collectors.toList() return?

孤街浪徒 提交于 2019-11-27 11:45:27
I am reading State of the Lambda: Libraries Edition , and am being surprised by one statement: Under the section Streams , there is the following: List<Shape> blue = shapes.stream() .filter(s -> s.getColor() == BLUE) .collect(Collectors.toList()); The document does not state what shapes actually is, and I do not know if it even matters. What confuses me is the following: What kind of concrete List does this block of code return? It assigns the variable to a List<Shape> , which is completely fine. stream() nor filter() decide what kind of list to use. Collectors.toList() neither specifies the

Java 8 Streams: Map the same object multiple times based on different properties

﹥>﹥吖頭↗ 提交于 2019-11-27 11:36:02
问题 I was presented with an interesting problem by a colleague of mine and I was unable to find a neat and pretty Java 8 solution. The problem is to stream through a list of POJOs and then collect them in a map based on multiple properties - the mapping causes the POJO to occur multiple times Imagine the following POJO: private static class Customer { public String first; public String last; public Customer(String first, String last) { this.first = first; this.last = last; } public String

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

≡放荡痞女 提交于 2019-11-27 10:30:33
I know how to "transform" a simple Java List from Y -> Z , i.e.: List<String> x; List<Integer> y = x.stream() .map(s -> Integer.parseInt(s)) .collect(Collectors.toList()); Now I'd like to do basically the same with a Map, i.e.: INPUT: { "key1" -> "41", // "41" and "42" "key2" -> "42 // are Strings } OUTPUT: { "key1" -> 41, // 41 and 42 "key2" -> 42 // are Integers } The solution should not be limited to String -> Integer . Just like in the List example above, I'd like to call any method (or constructor). Map<String, String> x; Map<String, Integer> y = x.entrySet().stream() .collect(Collectors

Why does Collectors.toMap report value instead of key on Duplicate Key error?

守給你的承諾、 提交于 2019-11-27 09:26:36
This is really a question about a minor detail, but I'm under the impression to get something wrong here. If you add duplicate keys using Collectors.toMap-method it throws an Exception with message "duplicate key ". Why is the value reported and not the key? Or even both? This is really misleading, isn't it? Here's a little test to demonstrate the behaviour: import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class TestToMap { public static void main(String[] args) { List<Something> list = Arrays.asList( new Something("key1", "value1

Java 8 grouping using custom collector?

不羁岁月 提交于 2019-11-27 05:25:57
I have the following class. class Person { String name; LocalDate birthday; Sex gender; String emailAddress; public int getAge() { return birthday.until(IsoChronology.INSTANCE.dateNow()).getYears(); } public String getName() { return name; } } I'd like to be able to group by age and then collect the list of the persons names rather than the Person object itself; all in a single nice lamba expression. To simplify all of this I am linking my current solution that store the result of the grouping by age and then iterates over it to collect the names. ArrayList<OtherPerson> members = new ArrayList