java-stream

Java 8 Collector that returns a value if there's only a single value [duplicate]

风格不统一 提交于 2019-12-02 17:29:13
This question already has an answer here: Filter Java Stream to 1 and only 1 element 18 answers I'm a little green on this functional programming and streams stuff, but what little I do know has been very useful! I've had this situation come up several times: List<SomeProperty> distinctProperties = someList.stream() .map(obj -> obj.getSomeProperty()) .distinct() .collect(Collectors.toList()); if (distinctProperties.size() == 1) { SomeProperty commonProperty = distinctProperties.get(0); // take some action knowing that all share this common property } What I really want is: Optional

Collectors.toSet() and HashSet

折月煮酒 提交于 2019-12-02 16:56:09
Take the following line of sample code: Set<String> someSet = someColletion.stream().map(p -> p.toString()).collect(Collectors.toSet()); I want a HashSet . Taking a debugger to the code, I am indeed getting a HashSet . I had a look at java.util.stream.Collectors.toSet() to observe the following code: public static <T> Collector<T, ?, Set<T>> toSet() { return new CollectorImpl<>((Supplier<Set<T>>) HashSet::new, Set::add, (left, right) -> { left.addAll(right); return left; }, CH_UNORDERED_ID); } The contract guarantees a Set , and implementation decides on a HashSet ; seems reasonable. However,

Collectors.toMap() keyMapper — more succinct expression?

喜夏-厌秋 提交于 2019-12-02 16:08:57
I'm trying to come up with a more succinct expression for the "keyMapper" function parameter in the following Collectors.toMap() call: List<Person> roster = ...; Map<String, Person> map = roster .stream() .collect( Collectors.toMap( new Function<Person, String>() { public String apply(Person p) { return p.getLast(); } }, Function.<Person>identity())); It seems that I should be able to inline it using a lambda expression, but I cannot come up with one that compiles. (I'm quite new to lambdas, so that's not much of a surprise.) Thanks. --> Update: As noted in the accepted answer Person::getLast

Java 8 stream unpredictable performance drop with no obvious reason

亡梦爱人 提交于 2019-12-02 16:04:45
I am using Java 8 streams to iterate over a list with sublists. The outer list size varies between 100 to 1000 (different test runs) and the inner list size is always 5. There are 2 benchmark runs which show unexpected performance deviations. package benchmark; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import java.io.IOException; import java.util.concurrent.ThreadLocalRandom; import java.util.*; import java.util.function.*; import java.util.stream.*; @Threads(32) @Warmup(iterations = 25) @Measurement(iterations = 5) @State(Scope.Benchmark) @Fork(1)

takeWhile() working differently with flatmap

夙愿已清 提交于 2019-12-02 15:41:58
I am creating snippets with takeWhile to explore its possibilities. When used in conjunction with flatMap, the behaviour is not in line with the expectation. Please find the code snippet below. String[][] strArray = {{"Sample1", "Sample2"}, {"Sample3", "Sample4", "Sample5"}}; Arrays.stream(strArray) .flatMap(indStream -> Arrays.stream(indStream)) .takeWhile(ele -> !ele.equalsIgnoreCase("Sample4")) .forEach(ele -> System.out.println(ele)); Actual Output: Sample1 Sample2 Sample3 Sample5 ExpectedOutput: Sample1 Sample2 Sample3 Reason for the expectation is that takeWhile should be executing till

Create only 1 list from a map where map value is list using JAVA 8 Streams

佐手、 提交于 2019-12-02 13:27:49
I have a Map, where the "value" is a List of projects: Map<User, List<Project>> projectsMap = ... I want to extract from the map the projects but in only and just 1 List of projects: I've already seen answers but they don't apply to my case. I don't want this result: List<List<Project>> theValueOfTheMap; The result I want is: List<Project> projects = ... // All the project in the value's map How can I achieve this using JAVA 8 Streams? Thanks. Leonardo. Thanks @Holger for the answer. List<Project> projects = projectsMap.values().stream().flatMap(List::stream) .collect(‌​Collectors.toList())‌​;

How does reduce() method work with parallel streams in Java 8?

半城伤御伤魂 提交于 2019-12-02 08:41:58
I try to understand how reduce() method works exactly with parallel streams and I don't understand why the following code do not return the concatenation of these strings. This is the code: public class App { public static void main(String[] args) { String[] grades = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"}; StringBuilder concat = Arrays.stream(grades).parallel() .reduce(new StringBuilder(), (sb, s) -> sb.append(s), (sb1, sb2) -> sb1.append(sb2)); System.out.println(concat); } } The code works only with sequential streams, but with parallel streams it doesn't return the

How Can I use Java Stream To Build a List<Integer> And The Integer Between a and b

大兔子大兔子 提交于 2019-12-02 03:17:57
Say I have two variables : a = 5 , b = 8 , And I want : Arrays.asList(5, 6, 7, 8) How Can I Use Java stream To get this? you can use IntStream.rangeClosed to generate the numbers and collect into a list. List<Integer> result = IntStream.rangeClosed(a, b) .boxed() .collect(Collectors.toList()); 来源: https://stackoverflow.com/questions/47975249/how-can-i-use-java-stream-to-build-a-listinteger-and-the-integer-between-a-and

Deadlock happens if I use lambda in parallel stream but it doesn't happen if I use anonymous class instead? [duplicate]

拟墨画扇 提交于 2019-12-02 00:37:56
This question already has an answer here: Why does parallel stream with lambda in static initializer cause a deadlock? 3 answers The following code leads to deadlock(on my pc): public class Test { static { final int SUM = IntStream.range(0, 100) .parallel() .reduce((n, m) -> n + m) .getAsInt(); } public static void main(String[] args) { System.out.println("Finished"); } } But if I replace reduce lambda argument with anonymous class it doesn't lead to deadlock: public class Test { static { final int SUM = IntStream.range(0, 100) .parallel() .reduce(new IntBinaryOperator() { @Override public int

Java 8 Stream of Super Classes, Parent Files, Component Parents, linked list, etc

帅比萌擦擦* 提交于 2019-12-01 20:33:48
问题 I would like to convert the following for statement to a Java 8 stream (i.e. Stream<Class<?>> ). The ideal solution would be simple enough that I can easily adapt it for a variety of situations of traversing a linked list (e.g. File.getParentFile() , Component.getParent() ). Class<?> clazz; Object value; value = ...; for (clazz = value.getClass(); clazz != null; clazz = clazz.getSuperclass()) ... I realize that a few lines of code to create a stream isn't going to be simpler than a single for