java-stream

A list contains at least one value from another list (Java 8)

▼魔方 西西 提交于 2019-12-04 09:51:27
My function finds if from a list of given words at list one word is valid in the page. So when page contains words I have written it as follows: (Simplified version) private boolean atLeastOneWordIsValidInThePage(Page page, Set<Long> wordIdsToCheck) Set<Long> wordIds = page.getWords().stream() .filter(word -> word.isValid()) .map(word->getWordId()) .collect(Collectors.toSet()); return words.stream().anyMatch((o) -> wordIds.contains(o)); Is it the best java 8 practice to write it? I want to stop searching when the first match is found. There is no need to open two separate streams. You should

How to Group Objects in a List into other Lists by Attribute using streams & Java 8?

孤街浪徒 提交于 2019-12-04 09:47:56
I want to group a List of Objects containing a time attribute into 5-Minute intervals, preferably using streams and collectors. The only possible solution I found on StackOverflow is to calculate how many intervals (sublists) I need, add every object to every one of these Lists and filter out the ones that dont fit into the respective timeframe, which is not exactly a nice solution. (You can find the Thread here: How to group elements of a List by elements of another in Java 8 ) I thought of something similar to this: List<MyObject> list = new ArrayList<MyObject>(); ....... List<List<MyObject>

stream collect accumulator/combiner order

随声附和 提交于 2019-12-04 09:25:10
问题 This is basically a follow-up of this answer of mine. Suppose that I am working on custom collector and supposing that the accumulator always will add some element to the collection returned by the supplier, is there any chance that when combiner is called, one of the intermediate results will be empty? An example is probably a lot simpler to understand. Suppose I have a List of numbers and I want to split it in List of Lists, where 2 is the separator. So for example I have 1, 2, 3, 4, 2, 8 ,

What's the simplest way to convert a String Array to an int Array using Java 8?

你。 提交于 2019-12-04 09:14:40
问题 I'm currently learning how to use Java and my friend told me that this block of code can be simplified when using Java 8. He pointed out that the parseIntArray could be simplified. How would you do this in Java 8? public class Solution { public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] tokens = input.nextLine().split(" "); int[] ints = parseIntArray(tokens); } static int[] parseIntArray(String[] arr) { int[] ints = new int[arr.length]; for (int i = 0;

Convert a for loop to concat String into a lambda expression

一世执手 提交于 2019-12-04 08:53:00
问题 I have the following for loop which iterates through a list of strings and stores the first character of each word in a StringBuilder . I would like to know how can I transform this to a lambda expression StringBuilder chars = new StringBuilder(); for (String l : list) { chars.append(l.charAt(0)); } 回答1: Assuming you call toString() on the StringBuilder afterwards, I think you're just looking for Collectors.joining(), after mapping each string to a single-character substring: String result =

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

痴心易碎 提交于 2019-12-04 08:49:25
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(s -> s.length() >= 2) .collect(Collectors.toConcurrentMap( w -> w, w -> 1, Integer::sum)); wc.entrySet

Java 8: Find index of minimum value from a List

瘦欲@ 提交于 2019-12-04 08:07:34
问题 Say I have a list with elements (34, 11, 98, 56, 43) . Using Java 8 streams, how do I find the index of the minimum element of the list (e.g. 1 in this case)? I know this can be done easily in Java using list.indexOf(Collections.min(list)) . However, I am looking at a Scala like solution where we can simply say List(34, 11, 98, 56, 43).zipWithIndex.min._2 to get the index of minimum value. Is there anything that can be done using streams or lambda expressions (say Java 8 specific features) to

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

一笑奈何 提交于 2019-12-04 07:45:02
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 here I see that in first case stream really behaves lazily - we use findFirst() so once we have first

How to eliminate duplicate entries within a stream based on a own Equal class

丶灬走出姿态 提交于 2019-12-04 07:32:51
I do have a simialar problem like descripted here . But with two differences first I do use the stream api and second I do have an equals() and hashCode() method already. But within the stream the equalitity of the of Blogs are in this context not the same as defined in the Blog class. Collection<Blog> elements = x.stream() ... // a lot of filter and map stuff .peek(p -> sysout(p)) // a stream of Blog .? // how to remove duplicates - .distinct() doesn't work I do have a class with an equal Method lets call it ContextBlogEqual with the method public boolean equal(Blog a, Blog b); Is there any

Collecting stream back into the same collection type

ⅰ亾dé卋堺 提交于 2019-12-04 07:01:57
Suppose I have a collection of the unknown type. What I want to do is stream it, do some stuff on the stream, and collect it back into the same collection type as my original collection. For instance: Collection<? extends Integer> getBigger(Collection<? extends Integer> col, int value) { return col.stream().filter(v -> v > value).collect(????); } The idea of this incomplete code example is to return a List if col is of List class (or any subclass of it), a Set if col is of Set class, etc... The method name and actual operations on the stream here are not important, I've specified them just to