java-stream

Java-8 stream expression to 'OR' several enum values together

旧街凉风 提交于 2019-12-06 15:43:14
I am aggregating a bunch of enum values (different from the ordinal values) in a foreach loop. int output = 0; for (TestEnum testEnum: setOfEnums) { output |= testEnum.getValue(); } Is there a way to do this in streams API? If I use a lambda like this in a Stream<TestEnum> : setOfEnums.stream().forEach(testEnum -> (output |= testEnum.getValue()); I get a compile time error that says, 'variable used in lambda should be effectively final'. Predicate represents a boolean valued function, you need to use reduce method of stream to aggregate bunch of enum values. if we consider that you have

How to convert type of stream?

南楼画角 提交于 2019-12-06 15:25:29
In addition to my question asked previously, that can be found here, How to combine list elements and find the price of largest combination Instead of using Integer price , I am using String price , List<Long> highest = details .stream() .map(d -> Stream.concat(Stream.of(d.getDetailId()), d.getStackableDetails().stream()).collect(Collectors.toList())) .collect(Collectors.toMap(s -> s.stream().map(Double.class::cast).reduce(0D, (left, right) -> left + Double.parseDouble(map.get(right).getPrice())), s -> s.stream().collect(Collectors.toList()), (left, right) -> right, TreeMap::new)) .lastEntry()

Java 8 turn on parallel() stream with boolean? [closed]

╄→гoц情女王★ 提交于 2019-12-06 14:15:24
Closed . This question is opinion-based . It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post . Closed 3 years ago . I am wondering how I could design methods that could either be run concurrently or single threaded. For example I have a method like this: /** * Produces the norm of the two vector {@code v1}. * * @param v1 * The first vector. * * @param v2 * The second vector * * @throws MathException * Of type {@code DIMENSION_MISMATCH} if * {@code v1.getDimension()} is != {@code v2

Collection.toArray() vs Collection.stream().toArray()

有些话、适合烂在心里 提交于 2019-12-06 14:05:51
Consider the following code: List<String> myList = Arrays.asList(1, 2, 3); String[] myArray1 = myList.toArray(new String[myList.size()]); String[] myArray2 = myList.stream().toArray(String[]::new); assert Arrays.equals(myArray1, myArray2); It seems to me that using a stream is much simpler. Therefore, I tested the speed of each. List<String> myList = Arrays.asList("1", "2", "3"); double start; start = System.currentTimeMillis(); for (int i = 0; i < 10_000_000; i++) { String[] myArray1 = myList.toArray(new String[myList.size()]); assert myArray1.length == 3; } System.out.println(System

Java 8 stream compare two objects and run a function on them

。_饼干妹妹 提交于 2019-12-06 13:26:14
I've a a stream which I want to partition into smaller parts based on matching Id and then apply some proccessing logic on each of the part/element. class BigRequest{ String bId; List<Parts> parts; //getters and setter here } Class Parts{ String pId; String partId; //getters and setter here } I want to segregate and create a list of Parts of size 10 when the partId of different parts are same. How to use the filter or reduce or groupingBy function to compare the two elements and put them to a list? I've tried filter like below, doesn't take p1 variable: big.stream().filter( p -> p.getPartId()

Java 8 Stream (based on resource) .iterator() that auto-closes the resource?

懵懂的女人 提交于 2019-12-06 12:03:25
Does Java 8 Stream.iterator() auto-close the stream when it's done? I suppose not... I have something like this: class Provider implements Serializable { Iterator<String> iterator() { Stream<String> stream = new BufferedReader(...).lines(); return stream.iterator(); } } This iterator is used by some other class that doesn't know the iterator is based on a file-reading resource. That is class Consumer { void f() { Iterator<String> iterator = provider.iterator(); // code that calls iterator methods at non-determined times } } I have to stream the file because it's too large to fit into memory.

How to effectively parse text files with Java Stream API

心已入冬 提交于 2019-12-06 12:02:44
问题 I understand how to get specific data from a file with Java 8 Streams. For example if we need to get Loaded package s from a file like this 2015-01-06 11:33:03 b.s.d.task [INFO] Emitting: eVentToRequestsBolt __ack_ack 2015-01-06 11:33:03 c.s.p.d.PackagesProvider [INFO] ===---> Loaded package com.foo.bar 2015-01-06 11:33:04 b.s.d.executor [INFO] Processing received message source: eventToManageBolt:2, stream: __ack_ack, id: {}, [-6722594615019711369 -1335723027906100557] 2015-01-06 11:33:04 c

Java8 stream operations are cached? [duplicate]

我的未来我决定 提交于 2019-12-06 10:50:36
This question already has an answer here : Java 8, first processing of a list is slower than the subsequent processing (1 answer) Closed 3 years ago . I ran below sample code in my PC running with Intel(R) Xeon(R) CPU E5-2680 0 @ 2.70GHz (2 CPUs), ~2.7GHz String format = "%7s run taken %6d micro seconds %5d findAny"; // First run long start = System.nanoTime(); int rand = IntStream.range(0, 100000).parallel().findAny().getAsInt(); long end = System.nanoTime(); System.out.println(String.format(format, "First", ((end - start) / 1000), rand)); // Subsequent runs for (int i = 0; i < 25; i++) {

Grouping a range of integers to the answer of a function

故事扮演 提交于 2019-12-06 10:25:58
问题 For a range of integers, I would like to apply an ("expensive") operation, filter out only those integers with interesting answers, then group on the answer. This first snippet works, but it duplicates the operation ("modulus 2") both in code and computation: IntStream.range(1, 10).boxed() .filter(p -> (p % 2 != 0)) // Expensive computation .collect(Collectors.groupingBy(p -> (p % 2))); // Same expensive // computation! // {1=[1, 3, 5, 7, 9]} (Correct answer) I tried mapping to the answer

Based on condition set object value and return boolean using java 8 streams

别说谁变了你拦得住时间么 提交于 2019-12-06 10:25:01
I have nested list and am able to set isMatched and department.setMatchedStatus(true) when if condition is true. boolean isMatched = false; for (Employee employee: company.getEmployees()) { for (Department department: employee.getDepartments()) { if(departmentList.contains(department.getDepartmentName())){ isMatched = true; department.setMatchedStatus(true); } } } return isMatched; Would like to achieve the same using java 8 streams, which i tried using below code, but couldn't return boolean. isMatched = company.getEmployees().stream() .flatMap(employee-> employee.getDepartments().stream())