FAQ Database Discussion Community


How can I find the largest M numbers from N numbers in Java 8?

java,algorithm,java-8,java-stream
IntStream may be a the easiest way but I can only pick up smallest M numbers as below: public class Test { private static final int[] arr = {5, 3, 4, 2, 9, 1, 7, 8, 6}; public static void main(String[] args) throws Exception { System.out.println(Arrays.asList(IntStream.of(arr).sorted().limit(5).boxed().toArray())); } } btw, considering...

Convert InputStream into Stream given a Charset

java,io,stream,java-8,java-stream
I want to convert an InputStream is into a Stream<String> stream given a Charset cs in such a way that stream consists of the lines of is. Furthermore a line of is should not be read immediately but only in case stream needs it.

Java 8: More efficient way of comparing lists of different types?

lambda,comparison,java-8,java-stream
In a unit test, I want to verify that two lists contain the same elements. The list to test is build of a list of Person objects, where one field of type String is extracted. The other list contains String literals. One often finds the following code snippet to accomplish...

Java stream map and collect - order of resulting container

java,list,java-8,java-stream
List<MyObject> myList; //populate myList here List<String> nameList = myList .stream() .map(MyObject::getName) .collect(Collectors.toList()); In above code, can I expect that order of MyObject names in nameList is always the same as the order of myList?...

Collector which returns array

lambda,java-8,java-stream
I have the following code: strings.stream().map( i->i.toUpperCase()).collect(Collectors.toList()); The code above returns List I want to achieve analog which will return array. Is it possible without additional toArray method invocation? ...

How to stop a reduce operation mid way based on some condition?

java-8,java-stream
How to stop a reduce operation mid way based on some condition? For example, how can I find an index of maximum value in a list of integers before hitting 0. So in code below, processing list1 should return 4 (5th element), while processing list2 should return 1 (2nd element,...

Java 8 stream from modified collection

java,multithreading,java-8,java-stream
Say I have a List of objects that being modified by only one thread (the thread can add or remove objects) and and another thread occasinally uses stream api from the above collecion to do some stream manipulation of it and at the end (eager operation) return a new collection....

How to print two lists together using Stream API java 8?

java,java-8,java-stream
I have two lists as follow List<String> names = Arrays.asList("James","John","Fred"); List<Integer> ages = Arrays.asList(25,35,15); What i want to do is to print those two lists like so James:25 John:35 Fred:15 It is easy to do it using the classic way for(int i=0;i<names.size();i++){ System.out.println(names.get(i)+":"+ages.get(i)); } Is there a way to do...

Iterate through collection, perform action on each item and return as List

java,java-8,java-stream
is there any way to do it with java 8 Stream API? I need to transform each item of collection to other type (dto mapping) and return all set as a list.. Something like Collection<OriginObject> from = response.getContent(); DtoMapper dto = new DtoMapper(); List<DestObject> to = from.stream().forEach(item -> dto.map(item)).collect(Collectors.toList()); public...

Method reference and chained predicate

java,java-8,predicate,java-stream,method-reference
I'm trying to compactify my code with method references. Here is a line that I'm trying to improve: assertThat("only true & false strings allowed", records.stream().map(Record::getType) .allMatch(s -> "true".equals(s) || "false".equals(s))); With method reference it could be much nicer: assertThat("only true & false strings allowed", records.stream().map(Record::getType).allMatch("true"::equals)); But can I anyhow add...

java 8 - stream, map and count distinct

java,java-8,java-stream
My first attempt with java 8 streams... I have an object Bid, which represents a bid of a user for an item in an auction. i have a list of bids, and i want to make a map that counts in how many (distinct) auctions the user made a bid....

How to work with Java 8 streams?

java,foreach,java-8,java-stream
I want to know how to work with Java 8 streams and how to use the different kind of available stream operations. For example, I wrote this part of code: ArrayList<State> toBeRemoved = new ArrayList<>(); for (State s : newStates) if (path.contains(s)) // path is a stack of State toBeRemoved.add(s);...

Java 8 lambdas nested Map

java,lambda,java-8,java-stream,collectors
I am trying to use Java-8 lambdas to solve the following problem: Given a List<Transaction>, for each Category.minorCategory I require the sum of Transaction.amount per Category.minorCategory and a Map of Transaction.accountNumber with the sum of Transaction.amount per Transaction.accountNumber. I have this working, as per the code below. I now have...

How to move specific objects to the beginning of a list using java 8 Stream API?

java,java-stream
Consider this list of String List<String> list = Arrays.asList("c", "k", "f", "e", "k", "d"); What i want to do is to move all k Strings to the beginning of the list and keep the rest at the same order. What i have tried so far (it is working but i...

Java 8 streaming API using with Map

lambda,functional-programming,java-8,java-stream
I see this code snippet at my work. I am unable to get correct picture of what is going on here. I tried using debugger to get values, but debugger is not helpful here. public static void process (ErrorCat exc, String toFind) { Map<String, Function<Error, Error>> translate = new HashMap<>();...

Java 8 Stream operation

java,lambda,java-8,java-stream
Let's say I have a Stream of Strings called s. Is it possible to have a unary operation that converts every lone String to two Strings? So if the original Stream contains {a,b,c} and the operation converts every single String s to s + "1" and s + "2" then...

Encounter Order wrong when sorting a parallel stream

java,parallel-processing,java-8,java-stream
I have a Record class: public class Record implements Comparable<Record> { private String myCategory1; private int myCategory2; private String myCategory3; private String myCategory4; private int myValue1; private double myValue2; public Record(String category1, int category2, String category3, String category4, int value1, double value2) { myCategory1 = category1; myCategory2 = category2; myCategory3...

Java8 internal iteration

java-8,java-stream
Does java8 forEach method use an iterator or not really? I google it to the bone, could not find it precisely. Only the fact that it will iterate in the same order the data are. Any tips?...

Java 8 stream map to list of keys sorted by values

java,collections,lambda,java-8,java-stream
I have map Map<Type, Long> countByType and I want to have a list which has sorted (min to max) keys by their corresponding values. My try is: countByType.entrySet().stream().sorted().collect(Collectors.toList()); however this just gives me a list of entries, how can I get a list of types, without losing the order?...

Externalizing the Predicate in Java Lambda Stream Filter

lambda,java-8,java-stream
I have a ArrayList of data-model which has 10 fields based on the user input I need to dynamically apply the Predicate condition on user selected field to Stream filter. Below snippet applied with one of the field itemDesc, but at the runtime user can select any field. Predicate<DataModel> contains...

Grouping by object value, counting and then setting group key by maximum object attribute

java,java-8,grouping,java-stream
I have managed to write a solution using Java 8 Streams API that first groups a list of object Route by its value and then counts the number of objects in each group. It returns a mapping Route -> Long. Here is the code: Map<Route, Long> routesCounted = routes.stream() .collect(Collectors.groupingBy(gr...

Java8 Nested Streams write back with setter

java,java-8,java-stream
I´m trying to loop over two lists, filter the nested list and write the result back into the main object with java8 features. locations.forEach(location -> location.getSubList().stream() .filter(this::correctTestDataValue) .collect(Collectors.toList())); So by now the sublist inside location doesnt change, which is obvious because stream and collect do create a new list, which...

Java 8 Stream Collecting Set

java,java-8,java-stream
To better understand the new stream API I'm trying to convert some old code, but I'm stuck on this one. public Collection<? extends File> asDestSet() { HashMap<IFileSourceInfo, Set<File>> map = new HashMap<IFileSourceInfo, Set<File>>(); //... Set<File> result = new HashSet<File>(); for (Set<File> v : map.values()) { result.addAll(v); } return result; }...

java8 stream grouping aggregate

sum,java-8,grouping,java-stream
Given a java class Something class Something { String parent; String parentName; String child; Date at; int noThings; Something(String parent, String parentName, String child, Date at, int noThings) { this.parent = parent; this.parentName = parentName; this.child = child; this.at = at; this.noThings = noThings; } String getParent() { return parent;...

Nested for each loop returning map with Java 8 streams

java,java-8,java-stream
I just started with Java 8 and streams, and not able to find out how to write this code in Java 8: Map<Integer, CarShop> result = new HashMap<>(); for (Car car : someListOfCars) { List<CarProduct> listOfCarProducts = car.getCarProducts(); for (CarProduct product : listOfCarProducts) { result.put(product.getId(), car.getCarShop()); } } Any help?...

Collect list of Long from Double stream in Java 8

java,java-8,java-stream
I have the following code: List<Long> list = new ArrayList<>(); list.add(4L); list.add(92L); list.add(100L); List<Long> newList = list.stream().map(i -> i * 2.5) .mapToLong(Double::doubleToRawLongBits) .collect(Collectors.toList()); This code doesn't work and the compilation error is: Error:(28, 96) java: method collect in interface java.util.stream.LongStream cannot be applied to given types; required: java.util.function.Supplier,java.util.function.ObjLongConsumer,java.util.function.BiConsumer found:...

Sorting (a stream of) doubles by absolute magnitude

java,java-8,java-stream
I have a series of double values which I want to sum up and get the maximum value. The DoubleStream.summaryStatistics() sounds perfect for that. The getSum() method has an API note reminding me of what I learned during one of my computer science courses: the stability of the summation problem...

Java 8: how to get the first number greater than 10 in a stream?

java,java-8,java-stream
As per subject: How can I get the first number greater than 10 in a stream? Is there any method of stream() that may help in this case? I would like that as soon as the stream reaches the first element above 10 it will return it without looping the...

How to check if any element in a list occurs x number of times with stream() in Java 8

java-8,java-stream
Say you have a Collection of cards, containing a suit and a face: Collection<Card> cards = Arrays.asList(new Card('H',6),new Card('H',3), new Card('H',9), new Card('H',4),new Card('S', 1), new Card('H', 2), new Card('D', 12), new Card('S',7), new Card('C', 13)); Recall poker rules; Using stream() in java 8, is there a pretty way of...

java 8 stream groupingBy sum of composite variable

java,sorting,java-8,grouping,java-stream
I have a class Something which contains a instance variable Anything. class Anything { private final int id; private final int noThings; public Anything(int id, int noThings) { this.id = id; this.noThings = noThings; } } class Something { private final int parentId; private final List<Anything> anythings; private int getParentId()...

Map to List

java,lambda,java-8,java-stream
I'm trying to convert a Map<String, String> to a List<String> using lambdas. Essentially I'd like to concatenate the key and value with an '=' in between. This seems trivial but I can't find how to do it. E.g. Map<String, String> map = new HashMap<>(); map.put("a1","b1"); map.put("a2","b2"); map.put("a3","b3"); // Lambda //...

A seemingly silly way of using the Stream API that leads to the need for Predicate

functional-programming,java-8,java-stream
A predicate on booleans seems a little silly to me (well, at least in the following scenario): static Set<A> aSet = ...; checkCondition(B b) { return aSet.stream() .map(b::aMethodReturningBoolean) .filter((Boolean check) -> check) .limit(1).count() > 0; } What I am doing is that given the object b, checking whether there is...

Get last n elements from stream

java,java-8,java-stream
I am wondering is there an alternative to List<X> lastN = all.subList(Math.max(0, all.size() - n), all.size()); with stream usage?...

Double a stream

java,java-8,java-stream
I want to double a Stream (no DoubleStream). Meaning I start with a stream and want to get a new stream where each element of the old stream is streamed twice. So 1,2,3,4,4,5 gives us 1,1,2,2,3,3,4,4,4,4,5,5. Is there such a stream operation?

Collectors.toSet() and HashSet

java,java-8,java-stream,collectors
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...

How to iterate a stream even if exceptions are thrown?

java,java-8,java-stream
stream.map(obj -> doMap(obj)).collect(Collectors.toList()); private String doMap(Object obj) { if (objectIsInvalid) { throw new ParseException("Object could not be parsed"); } } Problem: how can I throw the exception and make the stream iteration know that it should not break the whole iteration, but continue with the next element (and eventually log...

How to sum values in a Map with a stream?

java,java-8,java-stream,java-generics
I want the equivalent of this with a stream: public static <T extends Number> T getSum(final Map<String, T> data) { T sum = 0; for (String key: data.keySet()) sum += data.get(key); return sum; } This code doesn't actually compile because 0 cannot be assigned to type T, but you get...

Why are Java 8's functional-style constructs called “streams”?

java,java-8,java-stream
The term "stream" is traditionally thought of as related to I/O operations. What is the reason Java chose the term "stream" for their functional-style operations?

Apply a list of Functions to a Java stream's .map() method

java,lambda,functional-programming,java-8,java-stream
I map a stream of NameValuePairs with a lookupFunction (which returns a Function), like this: List<NameValuePair> paramPairs = getParamPairs(); List<NameValuePair> newParamPairs = paramPairs.stream() .map((NameValuePair nvp) -> lookupFunction(nvp.getName()).apply(nvp)) .flatMap(Collection::stream) .collect(toList()); But what if lookupFunction returned a Collection<Function> instead, and I wanted to perform a .map() with each of the returned Functions....

Concatenating parallel streams

java,parallel-processing,java-8,java-stream
Suppose that I have two int[] arrays input1 and input2. I want to take only positive numbers from the first one, take distinct numbers from the second one, merge them together, sort and store into the resulting array. This can be performed using streams: int[] result = IntStream.concat(Arrays.stream(input1).filter(x -> x...

How to use Java 8 streams to find all values preceding a larger value?

java,java-8,java-stream
Use Case Through some coding Katas posted at work, I stumbled on this problem that I'm not sure how to solve. Using Java 8 Streams, given a list of positive integers, produce a list of integers where the integer preceded a larger value. [10, 1, 15, 30, 2, 6] The...

Writing stream data in map back to a List

lambda,java-8,java-stream
I have a treemap with information. I can foreach through it and pick the fields I want to print or just create a class from. But I can't figure out the conversion from that and get it into a List<> Ideally I would like to have it returned as List<AssetMinuteTotals>...

Stack using the Java 8 collection streaming API

java,java-8,java-stream,java-collections-api
I have a method which generates an object each time I execute it, and I need to reverse the order with which I am getting them. So I thought the natural way to do it would be a Stack, since it is LIFO. However, the Java Stack does not seem...

How to create a two dimensional array from a stream in Java 8?

java,java-8,java-stream
I have a text file like this: ids.txt 1000 999 745 123 ... I want to read this file and load it in a two dimensional array. I expect to have an array similar to the one below: Object[][] data = new Object[][] { // { new Integer(1000) }, //...

Grouping a range of integers to the answer of a function

java,functional-programming,java-8,java-stream
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 !=...

Aggregate runtime exceptions in Java 8 streams

java,exception-handling,java-8,java-stream
Let's say I have a method which throws a runtime exception. I'm using a Stream to call this method on items in a list. class ABC { public void doStuff(MyObject myObj) { if (...) { throw new IllegalStateException("Fire! Fear! Foes! Awake!"); } // do stuff... } public void doStuffOnList(List<MyObject> myObjs)...

Difference between Java 8 streams and RxJava observables

java-8,java-stream,rx-java,observable
Are Java 8 streams similar to RxJava observables? Java 8 stream definition: Classes in the new java.util.stream package provide a Stream API to support functional-style operations on streams of elements. ...

Creating a Stream based on if both ordered elements are equal in two other streams

java,java-8,java-stream
I am trying to learn how to use Java Streams in a situation where I would normally do imperatively. So if I have stream 1 that looks like this: 1 4 3 5 6 9 4 1 ... and stream 2 looks like this 1 0 3 0 0 9...

Java 8 stream group by min and max

java,java-8,java-stream
Suppose you run an SQL query against an employees table: SELECT department, team, MIN(salary), MAX(salary) FROM employees GROUP BY department, team And in the java client you map the result set to a list of Aggregate instances by making a DAO call like below: List<Aggregate> deptTeamAggregates = employeeDao.getMinMaxSalariesByDeptAndTeam() And 'Aggregate'...

Why is the combiner of the Collector interface not consistent with the overloaded collect method?

java,java-8,java-stream
There is an overload method, collect(), in interface Stream<T> with the following signature: <R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) There is another version of collect(Collector<? super T,A,R> collector), which receives an object with the previous three functions. The property of the interface Collector corresponding to the...

From Java parallelstream spawns other parallelStreams and fails seldom

java,lambda,parallel-processing,java-8,java-stream
Considering the following function: public void execute4() { File filePath = new File(filePathData); File[] files = filePath.listFiles((File filePathData) -> filePathData.getName().endsWith("CDR")); List<CDR> cdrs = new ArrayList<CDR>(); Arrays.asList(files).parallelStream().forEach(file -> readCDRP(cdrs, file)); cdrs.sort(cdrsorter); } which reads a list of Files containing CDR and executes the readCDRP() which is this: private void readCDRP(List<CDR> cdrs,...

Split java.util.stream.Stream

java,java-8,java-stream
I have a text file that contains URLs and emails. I need to extract all of them from the file. Each URL and email can be found more then once, but result shouldn't contain duplicates. I can extract all URLs using the following code: Files.lines(filePath). .map(urlPattern::matcher) .filter(Matcher::find) .map(Matcher::group) .distinct(); I...

Optional does not handle null elements

java-8,java-stream
As I experimented Optional<T> does not handle null elements, so in the following example it throws a NullPointerException in the last statement: List<String> data = Arrays.asList("Foo", null, "Bar"); data.stream().findFirst().ifPresent(System.out::println); data.stream().skip(1).findFirst().ifPresent(System.out::println); So, I still have to explicitly deal with null and filter non-null elements, such as: data.stream() .filter(item -> item !=...

Iterate with hasNext() and next() over an asynchronously generated stream of elements

java,scala,asynchronous,iterator,java-stream
I have to implement an Iterator interface (as defined by a Java API), with hasNext() and next() methods, that should return result elements which originate from an asynchronously processed HTTP response (processed with Akka actors). Following requirements have to be satisfied: do not block and wait for the async operation...

Can Java 8 Streams operate on an item in a collection, and then remove it?

java,collections,java-8,filtering,java-stream
Like just about everyone, I'm still learning the intricacies (and loving them) of the new Java 8 Streams API. I have a question concerning usage of streams. I'll provide a simplified example. Java Streams allows us to take a Collection, and use the stream() method on it to receive a...

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

list,lambda,java-8,java-stream
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...

State in a java.util.function.Function

lambda,java-8,java-stream
Suppose that I have a class which implements java.util.function.Function. The Function needs to know about a start date and end date but these will be constant throughout the lifetime of the function. I'm considering implementing the Function with private final fields for the start and end dates, as the apply...

Collect results from parallel stream

java,parallel-processing,java-8,java-stream
I have a piece of code like this: List<Egg> eggs = hens.parallelStream().map(hen -> { ArrayList<Egg> eggs = new ArrayList<>(); while (hen.hasEgg()) { eggs.add(hen.getEgg()); } return eggs; }).flatMap(Collection::stream).collect(Collectors.toList()); But in this way I have to create an ArrayList for every hen, and eggs are not collected until a hen is 100%...

Best way to find maximum integer inside a string array?

java,java-8,java-stream
String[] array = new String[] {"1", "2", "3", "25"}; I want to find the maximum number inside that string and return it as an integer. What is the best way, especially with regards to performance as I have to parse a few million rows with it? Two solutions I can...

Does Jackson support java 8 stream()?

json,jackson,java-8,guava,java-stream
I would like to use Jackson's Tree Model with Java 8 stream API, like so: JsonNode jn = new ObjectMapper().readValue(src, JsonNode.class); return jn.stream().anyMatch(myPredicate); However, JsonNode does not seem to implement stream() and I could not find any standard helpers to do so. JsonNode implements Iterable, so I can achieve the...

Why can I call the stream() method on objects of a class that don't have the stream()-method?

java,collections,syntax,java-stream
I'm a novice Java programmer at university. I discovered something today that broke one of my conceptions about how Java syntax works. public class testClass { ArrayList <String> persons = new ArrayList <String> (); public void run(){ Stream <String> personstream = persons.stream(); }} The method stream() is not found in...

Java 8 streams, lambdas

java,lambda,java-8,java-stream
I am trying to learn how to utilize Java 8 features(such as lambdas and streams) in my daily programming, since it makes for much cleaner code. Here's what I am currently working on: I get a string stream from a local file with some data which I turn into objects...

Java 8 stream partitioningBy second predicate on false condition

java,java-8,java-stream
I've been using streams as much as possible in my code recently but I've run into a problem I haven't quite been able to solve. I have a simple class called 'Listing': package models; public class House { private boolean isPrivate; private Integer views; private boolean hasSessionId; public Listing(boolean isPrivate,...

estimateSize() on sequential Spliterator

java,java-8,java-stream,spliterator
I'm implementing a Spliterator that explicitly restricts parallelization by having trySplit() return null. Would implementing estimateSize() offer any performance improvements for a stream produced by this spliterator? Or is the estimated size only useful for parallelization? EDIT: To clarify, I'm specifically asking about an estimated size. In other words, my...

Why don't primitive Stream have collect(Collector)?

java,java-8,java-stream,api-design
I'm writing a library for novice programmers so I'm trying to keep the API as clean as possible. One of the things my Library needs to do is perform some complex computations on a large collection of ints or longs. There are lots of scenarios and business objects that my...

How i can get list from some class properties with java 8 stream

java,collections,java-8,java-stream
Good day. I have a list of Person. I need get a list from property of Person. For example i have a Person class: class Person{ private String name; private String birthDate; public String getName(){ return name; } public String getBirthDate(){ return birthDate; } Person(String name){ this.name = name; }...

Do the common terminal operations not work with Stream?

java,byte,java-8,java-stream
I have a simple Stream that is meant to work on Bytes: List<Byte> byteList = Arrays.stream(new Byte[]{0x1, 0x2, 0x3, 0x4}) .map(b -> b >> 1) .collect(Collectors.toList()); The compiler gives: Error: incompatible types: inference variable T has incompatible bounds equality constraints: java.lang.Byte lower bounds: java.lang.Integer And this also does not work:...

Streaming the map and modifying it in Java 8

java,java-8,java-stream
I know that once we create the stream off of a collection we should not modify collection while consuming the stream, However not sure if following approach works where I am modifying the entry inside the map and not adding or removing anything from it. Also, is this the right...

Collect stream with grouping, counting and filtering operations

java,java-8,java-stream
I'm trying to collect stream throwing away rarely used items like in this example: import java.util.*; import java.util.function.Function; import static java.util.stream.Collectors.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import org.junit.Test; @Test public void shouldFilterCommonlyUsedWords() { // given List<String> allWords = Arrays.asList( "call", "feel", "call", "very", "call", "very", "feel", "very", "any"); //...

Why doesn't this Java 8 stream example compile?

java,java-8,type-inference,java-stream
I'm trying to figure out why this code does not compile on JDK 1.8.0_45: public class Example<E extends Example<E>> { public List<? extends Example<?>> toExamples(Collection<String> collection) { return collection.stream() .map(v -> lookup(v)) .collect(Collectors.toList()); } public static <E extends Example<E>> E lookup(String value) { return null; } } Adding a seemingly...

Sort Map by value reversed

sorting,dictionary,java-8,java-stream
I have a Map<String, Long> map which I want to sort by the Long value in reversed order using the features of Java 8. With Google I found this thread which provides this solution Map<String, Long> sortedMap = map.entrySet().stream() .sorted(comparing(Entry::getValue)) .collect(toMap(Entry::getKey, Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new)); If I want to...

One line check if String contains bannedSubstrings

java,string,lambda,java-8,java-stream
I have a String title and a List<String> bannedSubstrings. Now I want to perform a one line check if title is free of those bannedSubstrings. My approach: if(bannedSubstrings.stream().filter(bannedSubstring -> title.contains(bannedSubstring)).isEmpty()){ ... } Unfortunately, there is no isEmpty() method for streams. So how would you solve the problem? Is there a...

How to get the index and max value of an array in one shot?

java-8,java-stream
Given a list of integer elements, how to get the max value and it's index in one shot. If there is more than one element with same max value, returning index of any one of them is fine. For example: // Initialize list of integer List<Integer> intList = Arrays.asList(5, 8,...

Java 8 stream unpredictable performance drop with no obvious reason

java,performance,lambda,java-stream,jmh
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...

Using streams with custom functional interfaces

java,lambda,java-8,java-stream,functional-interface
I have just started looking at streams on this Oracle website. One question which immediately came to me looking at code like the one below is: what if I want to reuse the filter logic, e.g. having a method "isAdult" in Person? This won't work in streams as a method...

How to properly close a variable amount of streams?

java,java-8,java-stream,try-with-resources
I'm creating multiple streams which I have to access in parallel (or possibly-parallel). I know how to make a try-with-resources when the amount of resources is fixed at compile-time, but what if the amount of resources is determined by a parameter? I have something like this: private static void foo(String...

Collection being updated while performing stream operation java 8

java,java-8,java-stream
I have a List of objects that are being updated on a regular basis from a couple of threads. While being updated I want to use a stream to filter some elements out. For example; say I have list that is being updated regularly: List<MyObject> myList Now at some point...

Find a single object in a collection, HashMap vs List filter

java,java-8,java-stream
I generate a list of Customer from a file that I read. I store these customers in a HashMap where the key is a unique id : Map<String, Customer> customers = readCustomers(); //For each object created customers.put(c.getCustomerId(), c); From a second file I get data that I use to update...

java8 stream - filter map and aggregate

java-8,java-stream
Lets say I have a list of rooms List<Room> rooms; And each room has a list of persons. Using java8 streams I want to iterate the list of rooms, get all persons, execute some method on each node (doSomething()) and get a list of all the filtered objects. Is this...

How collectors are used when turning the stream in parallel

java,multithreading,java-8,java-stream,collectors
I actually tried to answer this question How to skip even lines of a Stream<String> obtained from the Files.lines. So I though this collector wouldn't work well in parallel: private static Collector<String, ?, List<String>> oddLines() { int[] counter = {1}; return Collector.of(ArrayList::new, (l, line) -> { if (counter[0] % 2...

Why does Stream.allMatch() return true for an empty stream?

java,lambda,java-8,java-stream
My colleague and I had a bug that was due to our assumption that an empty stream calling allMatch() would return false. if (myItems.allMatch(i -> i.isValid()) { //do something } Of course, it is kind of our fault for assuming and not reading documentation. But what I don't understand is...

Java 8 collector for Guava immutable collections?

java,guava,java-stream
I really like Java 8 streams and Guava's immutable collections, but I can't figure out how to use the two together. For example, how do I implement a Java 8 Collector that gathers stream results into an ImmutableMultimap? Bonus points: I'd like to be able to provide key/value mappers, similar...

java8 stream grouping and sorting on aggregate sum

java-8,grouping,aggregate,java-stream
Given a java class Something class Something { private int parentKey; private String parentName; private int childKey; private int noThings; public Something(int parentKey, String parentName, int childKey, int noThings) { this.parentKey = parentKey; this.parentName = parentName; this.childKey = childKey; this.noThings = noThings; } public int getParentKey() { return this.parentKey; }...

Parallel stream creates only one thread and gives result as fast as normal stream

multithreading,java-8,java-stream
Below is the code where I try to process lines read by from the file in parallel stream and in Normal stream. Surprisingly, parallel stream gives no improvements over normal stream . Am I missing something here ? Files.walk(Paths.get(tweetFilePath + LocalDate.now())).forEach( filePath -> { if (Files.isRegularFile(filePath) && !filePath.toString().endsWith(".DS_Store")) { long...

Java 8 Streams - Throwing an exception in the middle of an iteration

exception,java-8,java-stream
I have the following array ArrayList<Car> list = new ArrayList. I want to iterate it and throw an exception if it contains a certain value i.e. if at least one list.stream.filter(x-x.color.equals("Black")) then I want to stop iteration and throw an exception. Is there a way?...

Java 8, using .parallel in a stream causes OOM error

java,parallel-processing,java-8,java-stream
In the book Java 8 In Action, section 7.1.1, the authors state that a stream can benefit from parallel processing by adding the function .parallel(). They provide a simple method called parallelSum(int) to illustrate this. I was curious to see how well it worked so I executed this code: package...

functional way to accumulate pairs in java8

java,functional-programming,java-8,java-stream
Here's some imperative code that I'm trying to translate into functional programming code: public class Person { String name; Token token; public Person(String name, Token token) { this.name = name; this.token = token; } } public class Token { String id; boolean isValid; public Token(String id, boolean isValid) { this.id...

Filtering collection stream inside collection stream before returning

java,collections,lambda,java-stream
Background information I've got the following classes: Insurance public class Insurance { ... } Customer public class Customer { private List<Insurance> insurances; public List<Insurance> getInsurances() { return insurances; } ... } CustomerRegistry public class CustomerRegistry { private List<Customer> customers; ... } as well as this helper method, which reduces a...

Why does parallelStream not use the entire available parallelism?

java,multithreading,java-8,java-stream,fork-join
I have a custom ForkJoinPool created with parallelism of 25. customForkJoinPool = new ForkJoinPool(25); I have a list of 700 file names and I used code like this to download the files from S3 in parallel and cast them to Java objects: customForkJoinPool.submit(() -> { return fileNames .parallelStream() .map((fileName) ->...

Where is defined the combination order of the combiner of collect(supplier, accumulator, combiner)?

java,java-8,java-stream
The Java API documentations states that the combiner parameter of the collect method must be: an associative, non-interfering, stateless function for combining two values, which must be compatible with the accumulator function A combiner is a BiConsumer<R,R> that receives two parameters of type R and returns void. But the documentation...

How to sum a list of integers with java streams?

java,java-8,java-stream
I want to sum a list of integers. It works as follows, but the syntax does not feel right. Could the code be optimized? Map<String, Integer> integers; integers.values().stream.mapToInt(i -> i).sum(); ...

Splitting objects inside Java stream

java,java-8,java-stream,method-reference
I am wondering is it possible to split an object inside stream. For example for this Employee: public class Employee { String name; int age; double salary; public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public String getName() { return...

Java Streams API summing Lists at index

java,java-8,java-stream
i would like to know if there is a more efficient way to sum all tree lists - summing their values at the same index. The reason why i am asking its because, probably using Streams API, its possible to make it more generic, for any number of lists. List<Double>...

Java 8 lambdas grouping by multiple fields

java,java-8,java-stream,collectors
I have a list of pojos that I want to perform some grouping on. Something like: public class Pojo { private final Category category; private final BigDecimal someValue; } public class Category { private final String majorCategory; private final String minorCategory; } I want a Map<String, Map<String, List<Pojo>>> where the...

Builder pattern with a Java 8 Stream

java,java-8,builder,java-stream
I am building an object with a simple loop: WebTarget target = getClient().target(u); for (Entry<String, String> queryParam : queryParams.entrySet()) { target = target.queryParam(queryParam.getKey(), queryParam.getValue()); } I want to do the same thing using the Java8 Stream API but I cannot figure out how to do it. What makes me struggle...

Unable to get a response with Lambda Stream Filter [duplicate]

java,filter,java-stream
This question already has an answer here: How do I compare strings in Java? 23 answers Here is the stream "airportFilteredList" i am having trouble with, it should print the country name that matches the filter of the given "Turkey" string but it doesn't print anything to the console,...

How are lazy streams implemented in Java 8?

java-8,java-stream
I am reading Java 8, specifically the "Streams API". Wanted to know how the streams are lazy? I believe Streams are just added as library and there are no changes done to language to support laziness. Also, I will be shocked if somebody tells me it's achieved through reflections....

Populating a List with a contiguous range of shorts

java,java-8,java-stream
http://stackoverflow.com/a/23675131/14731 provides a nice solution for generating a list of contiguous integers. Seeing as JDK8 does not provide a ShortStream class, how would you generate a list of contiguous shorts? I'm looking for something along the lines of: List<Short> range = ShortStream.range(0, 500).boxed().collect(Collectors.toList()); where the output contains a list of...

How to use Java 8 Collectors groupingBy to get a Map with a Map of the collection?

java-8,java-stream,collectors
Imagine these classes class Subject{ private int id; private Type type; private String origin; private String name; Subject(int id, Type type, String origin, String name){ this.id = id; this.type = type; this.origin = origin; this.name = name; } //Getters and Setters } enum Type{ TYPE1, TYPE2 } I have a...

How to insert a counter into a Stream .forEach()?

java,foreach,java-stream,line-numbers
FileWriter writer = new FileWriter(output_file); int i = 0; try (Stream<String> lines = Files.lines(Paths.get(input_file))) { lines.forEach(line -> { try { writer.write(i + " # " + line + System.lineSeparator()); } catch (Exception e) { e.printStackTrace(); } } ); writer.close(); } I need to write the line with the line number,...