java-stream

Why filter() after flatMap() is “not completely” lazy in Java streams?

吃可爱长大的小学妹 提交于 2019-12-06 03:49:28
问题 I have the following sample code: System.out.println( "Result: " + Stream.of(1, 2, 3) .filter(i -> { System.out.println(i); return true; }) .findFirst() .get() ); System.out.println("-----------"); System.out.println( "Result: " + Stream.of(1, 2, 3) .flatMap(i -> Stream.of(i - 1, i, i + 1)) .flatMap(i -> Stream.of(i - 1, i, i + 1)) .filter(i -> { System.out.println(i); return true; }) .findFirst() .get() ); The output is as follows: 1 Result: 1 ----------- -1 0 1 0 1 2 1 2 3 Result: -1 From

Java 8 streams - How to extract all objects inside a map of maps to a new map?

前提是你 提交于 2019-12-06 03:45:20
I have a map of maps siteId -> (AppName -> App) I want to iterate all of the Apps in the inner map and create a new map of (appId -> App) I do it without stream Map<String, App> result = new HashMap<>(); siteIdToAppNameToAppMap.forEach((siteId, map) -> map.forEach((appName, app) -> result.put(app.token, app) ) ); How do I do it with stream? What about something like this? siteIdToAppNameToAppMap.values() .stream() .flatMap(m -> m.values().stream()) .collect( Collectors.toMap(App::getToken, Function.identity()) ); We will need to use Stream#flatMap to extract App from nested map. So stream()

List of Only One Single value of Filtered List Value

假如想象 提交于 2019-12-06 03:09:07
I want to do divide and conquers to solve this question I have this class before shown in my question Generate List with Combination of Subset of List, Java I have a class named Competitor, with Type, Name and Power. public class Competitor { private final int type; private final String name; private final int power; public Competitor(int type, String name, int power) { this.type = type; this.name = name; this.power = power; } public int getType() { return type; } public String getName() { return name; } public int getPower() { return power; } @Override public String toString() { return

Call a method on the return value of a method reference

大兔子大兔子 提交于 2019-12-06 03:02:50
问题 I have a stream of files that I want to filter based on the ending of the file name: public Stream<File> getFiles(String ending) throws IOException { return Files.walk(this.path) .filter(Files::isRegularFile) .map(Path::toFile) .filter(file -> file.getName().endsWith(ending)); } While the lambda in the last line is not bad, I thought I could use method references there as well, like so: .filter(File::getName.endsWith(ending)); Or alternatively wrapped in parentheses. However, this fails with

Improving the Java 8 way of finding the most common words in “War and Peace”

爷,独闯天下 提交于 2019-12-06 02:56:00
问题 I read this problem in Richard Bird's book: Find the top five most common words in War and Peace (or any other text for that matter). Here's my current attempt: public class WarAndPeace { public static void main(String[] args) throws Exception { Map<String, Integer> wc = Files.lines(Paths.get("/tmp", "/war-and-peace.txt")) .map(line -> line.replaceAll("\\p{Punct}", "")) .flatMap(line -> Arrays.stream(line.split("\\s+"))) .filter(word -> word.matches("\\w+")) .map(s -> s.toLowerCase()) .filter

when calculate a^b why parallel not work but parallelStream could

微笑、不失礼 提交于 2019-12-06 02:41:05
I want to calculate a^b , e.g. 2^30, public long pow(final int a, final int b) first I used this manner return LongStream.range(0, b).reduce(1, (acc, x) -> a * acc); // 1073741824 Got right result. Then I want to calculate it parallelly, so naturally I changed it to return LongStream.range(0, b).parallel().reduce(1, (acc, x) -> a * acc); // 32 but in this case the result is just 32 . Why? So for supporting parallel I changed it again return Collections.nCopies(b,a).parallelStream().reduce(1, (acc, x) -> acc * x); // 1073741824 in this case it works. So what's wrong with parallel manner? reduce

How can I reverse one single string in Java 8 using Lambda and Streams?

梦想与她 提交于 2019-12-06 02:34:12
问题 I have one string say "Aniruddh" and I want to reverse it using lambdas and streams in Java 8. How can I do it? 回答1: Given a string like String str = "Aniruddh"; the canonical solution is String reversed = new StringBuilder(str).reverse().toString(); If, perhaps for educational purposes, you want to solve this by streaming over the string’s characters, you can do it like String reversed = str.chars() .mapToObj(c -> (char)c) .reduce("", (s,c) -> c+s, (s1,s2) -> s2+s1); This is not only much

Java 8 Spliterator (or similar) that returns a value iff there's only a single value

只愿长相守 提交于 2019-12-06 02:27:56
问题 I'm a big fan of the singleOrEmpty stream operator. It's not in the std lib, but I find it very useful. If a stream has only a single value, it returns that value in an Optional . If it has no values or more than one value, it returns Optional.empty() . Optional<Int> value = someList.stream().{singleOrEmpty} [] -> Optional.empty() [1] -> Optional.of(1) [1, 1] -> Optional.empty() etc. I asked a question about it earlier and @ThomasJungblut came up with this great implementation: public static

Java 8 Streams: How to call once the Collection.stream() method and retrieve an array of several aggregate values [duplicate]

北城余情 提交于 2019-12-06 01:58:55
This question already has an answer here: How to get minimum and maximum value from List of Objects using Java 8 2 answers I'm starting with the Stream API in Java 8. Here is my Person object I use: public class Person { private String firstName; private String lastName; private int age; public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } } Here is my code which initializes a list

java8 stream sum multiple

你说的曾经没有我的故事 提交于 2019-12-06 01:35:27
问题 I am curious, how to sum up multiple variables in a java8 stream. Integer wCPU = 0; Double wnetwork = 0.0; Double wMem = 0.0; this.slaContractList.forEach(sla -> { wCPU += sla.getNumberOfCPUs(); wnetwork += sla.getNetworkBandwith(); wMem += sla.getMemory(); }); However, this does not compile as the variable in the lambda expression should be final. 回答1: Assuming slaContractList is a list of SlaContract objects, and it has constructor SlaContract(numberOfCPUs, networkBandwith, memory) you can: