Questions tagged [java-stream]

Use this tag for questions related to the use of the Stream API. It was introduced in Java 8 and supports functional-style operations on streams of values, such as filter-map-reduce pipelines on collections.

1
vote
2answers
53 views

Java 8 distinct() does not invoke the equals method

In Java 8, the docs for distinct() intermediate operation state Returns a stream consisting of the distinct elements (according to >Object.equals(Object)) of this stream. For ordered streams, ...
5
votes
3answers
56 views

Java Stream Collectors of array of objects

I have a list of array of 2 objects: List<Object[2]> Where object[0] is an Integer and object[1] is a String. How can I stream the list and apply different functions on each object? So that, ...
-3
votes
3answers
42 views

Identify record that is culprit - coding practices

Is method chaining good? I am not against functional programming that uses method chaining a lot, but against a herd mentality where people mindlessly run behind something that is new. The example, ...
0
votes
0answers
58 views

Java 8: How to stream a list into a list of lists?

Given a list of objects that need to be sorted and grouped: static class Widget { // ... public String getCode() { return widgetCode; } public String getName() { return widgetName; } } ...
0
votes
0answers
83 views

List as stream if present or else doesn't update the list?

UPDATE: I fixed my problem with this Optional<Collection<Pair<String, Integer>>> collResult = shufflingResult.stream().filter(c -> c.contains(uniquePair)).findAny(); if(...
0
votes
2answers
44 views

Sorting LongAdder in streams

I have Map<String,LongAdder> and I want to sort by the value the best way in streams. This is harder than with Long because LongAdder does not implement Comparable so I have to use longValue (...
-4
votes
1answer
48 views

How to Map two List Of type String in third List of Object [on hold]

I want to convert two List of String type into List of Person first List contain the firstname of person and 2nd list contain lastname which i want to map in List of Person Object class Person { ...
0
votes
1answer
22 views

problems getting filenames only from root folder and skipping its sub directories using java Files.walk

I have a folder with three files and 2 sub folders. I am only trying to read the path including file names as string from this root folder, however only condition is that i want to exclude other ...
-2
votes
2answers
54 views

Match Java Map keyset values with String values of a Java list of objects

I have a Java list of objects which each one contains a String value (code). Also I have a Java Map. I want to check whether all the elements in the Map keys are included in the list of the String ...
-2
votes
2answers
49 views

Java8 HashMap inside another Hashmap, how to find salary sum

I have a structure as shown below. I am trying to calculate the sum of all employee salaries. I would like to use Java streams. Could someone please explain how I can achieve this? Employee has a ...
2
votes
2answers
69 views

How to split a stream into multiple stream based on certain criteria?

I have a list of integers and I want to return sub lists of integers from this list using java 8 streams where my sub list contain all the positive integers from original list just before it ...
1
vote
1answer
48 views

Understading Java types for stream operations

When using stream, very similar two pieces of code behave differently. I cannot understand what the compiler's error is trying to convey. import java.util.Arrays; import java.util.List; import java....
3
votes
3answers
62 views

Filter list based on distinct and second predicate

My object looks like following Store { String shopId; long distance; } I got a list of stores. List<Store> storesList = Arrays.asList( new Store (1, 1), new Store (1, 5), ...
-1
votes
0answers
71 views

How to convert list of Reponse objects to a single sorted String output with Java 8 stream api? [on hold]

I have a Response class like this : public class Response { private boolean error; private String message; public Response(boolean error, String message) { this.error = error; ...
4
votes
3answers
73 views

Using Streams filter Map based on a list of keys

I have a particular problem and was wondering whether the Java 8 Streams API could solve it. I know that this can be done outside of using Streams API but I don't want to add all the boilerplate code ...
5
votes
2answers
70 views

Using Java 8 Streams' Collectors to increment value based of existing key/value pair

Suppose there is a List<Object> and that Object contains two methods: getUserId and getPoints. Consider that List<Object> contains three objects, and they contain the following data: ...
6
votes
4answers
106 views

Java Comparator with null fields

I have a list of entities Entity with the fields id and createdDate. I want to sort them as following: higher id first if id null, most recent createdDate first I've tried the following ...
5
votes
5answers
96 views

Transform a flat list to domain objects with child objects using java streams

I have incoming objects with a flat de-normalized structure which I instantiated from a JDBC resultset. The incoming objects mirror the resultset, there's loads of repeated data so I want to convert ...
0
votes
2answers
120 views

Streams in Java are much slower than native for loop - why? [duplicate]

To my understanding streams are faster than conventional old programing. However, when I ran following code the result is something I did not expect. public class Application { public static ...
7
votes
4answers
136 views

Implementing custom intermediate operations on Java 8 Streams

I'm trying to work out how to implement a custom intermediate operation on a Java 8 Stream. And it seems that I'm locked out :( Specifically I want to take a stream and return every entry up to and ...
-3
votes
0answers
37 views

How to know if a piece of code in a parallel stream is still running

I need to make a thread wait for other thread in a parallel stream to finish before executing the next block of code parallelStream().forEach( e-> { //run block of code //if done ...
-4
votes
0answers
52 views

How Can I use stream here? [on hold]

Just trying to use stream in the kotlin, can anyone help me how can i do that with the below code ? val valPair: Pair<MutableList<check>, MutableList<unit>> var hashMap:HashMap<...
4
votes
3answers
60 views

Local variable i defined in an enclosing scope must be final or effectively final

I want to implement this endpoint with internal search: @PostMapping("terminals_risk_filter/change_order/{terminalId}") public ResponseEntity<?> updateFiltersPositions(@PathVariable Integer ...
24
votes
6answers
1k views

How to remove multiple elements from Set/Map AND knowing which ones were removed?

I have a method that has to remove any element listed in a (small) Set<K> keysToRemove from some (potentially large) Map<K,V> from. But removeAll() doesn't do, as I need to return all keys ...
1
vote
1answer
30 views

Memory leak with Spring MongoDB stream?

The code below causes presumably memory leak: public int reregister(ReregisterDTO reregisterDTO) { AtomicInteger count = new AtomicInteger(0); StreamUtils.createStreamFromIterator( ...
0
votes
0answers
33 views

It's parallel stream method anyMatch(), allMatch(), noneMatch() allways short-circuiting?

I've been trying to make a parallel stream performance using short-circuiting operations like allMatch, noneMatch and anyMatch, are always applicable?
2
votes
3answers
73 views

Java Stream lifecycle callbacks

Does there exist an elegant way to register callbacks when the last element of the stream has been processed and the stream is "consumed" fully? Especially when the stream source (like a DB cursor, ...
1
vote
1answer
48 views

Why Pipeline grouping using Java's stream API collectors taking more time?

I'm creating a Map of Map from a list using Stream API. List contains 10 million records. I have done this with single statement using two 'groupingBy' operations as below. The problem is that this ...
1
vote
2answers
32 views

findAny from nested List using Java Streams

I need to find some object from nested List. I believe the class code is not needed, because the filtering is exposed in nested For-Each Loop. int value = someValue; MyObject found = null; for (...
0
votes
0answers
29 views

Can parallel() be used with sorted()? [duplicate]

I was curious whether parallel() can be used with sorted(), so I wrote a quick test: List<Integer> testArray = ImmutableList.of(3, 4, 2, 1, 5, 7, 2, 3, 4, 54, 1, 5, 1, 3, 2, 5, 1, 3, 4, 5, 6, 3,...
2
votes
3answers
87 views

Getting the max occurences of each individual number from a HashMap<Integer, List<Integer>>

I've been dealing with an exercise, in which I have to find a solution for the following problem: I have a HashMap<Integer, List<Integer>> and I have to get a List containing each of ...
-2
votes
0answers
63 views

Refactoring for loop to Java 8 parallel stream

public Double getTotal() { Double totalAmount = 0D; long memberCount = 200; List<Fee> fees = feesMngr.all(); for (FeeDto fee : fees) { if(fee.type.equals(FeeType....
0
votes
1answer
66 views

How to distinguish between true and false with partitioningby?

I am using java streams to separate the values "true" and "false" according to a certain condition, but they are all values counted as "false" I have this code: Map<String ,Map<Boolean,Long>&...
5
votes
3answers
80 views

Collectors.toMap write a merge function on a property of object which is not used a value

I am creating a Map<String,String> from List<Person> using java-8 stream persons.stream() .collect(Collectors.toMap(Person::getNationality, Person::getName, (name1, name2) -> ...
1
vote
1answer
68 views

Cannot resolve constructor in Java 8

I want to create a cloned list. I am using the below code snippet, but my IDE is showing a compilation error as "Cannot resolve constructor" even though MyClass has a default constructor. List<...
-2
votes
0answers
31 views

Why is applying reduce on this stream of objects results a compilation error and how to fix it? [duplicate]

I have a simple Gradle project: plugins { id 'java' id 'application' } repositories { mavenCentral() } sourceCompatibility = '11' targetCompatibility = '11' mainClassName = 'demo.Main' ...
0
votes
2answers
29 views

Custom Collector to join stream on delimiter, suffix and prefix only if stream is not empty suffix

I have a stream of strings: Stream<String> stream = ...; I want to create a string using stream.collect(Collectors.joining(',', '[', ']')) only I want to return "No Strings" if the stream ...
0
votes
1answer
52 views

How to sort a Map by value with java stream?

I wanted to sort my map by value, but I do not know how to do it. I have this code to put the values in the map: Map<Tuple7<Integer, String, Double, String, String, String, String>, Double&...
0
votes
1answer
37 views

Stream of elements between two objects?

I have an own implemented Queue. The Queue has two nodes, the front and end. Now I want to implement a size method with a Stream. I want to make a Stream between the two nodes and return the size of ...
1
vote
4answers
48 views

Create list of an element of an Object from another list of Objects

The model: public class MyModel{ private int id; private String name; .... .... //getters and setters } I have a list of MyModel object: //First Object to be added to list ...
1
vote
2answers
98 views

What is wrong with this Optional<Class> here?

I am trying to iterate list of objects Optional<QueryEntities> entities = InputYamlProcessor.process(ymlFilename); entities.orElseThrow( ()->{ logger.error("Unable to ...
-3
votes
4answers
100 views

How to return false if a java collection contains two identical elements

I have a Collection<Event>. Event looks something like this public class Event { private Integer id; private LocalDateTime localDateTime; // getters, setters omitted } Each Event ...
6
votes
3answers
101 views

Why do I need to map IntStream to Stream<Character>

public static int construction(String myString) { Set<Character> set = new HashSet<>(); int count = myString.chars() // returns IntStream .mapToObj(c -> (char)c) ...
3
votes
1answer
24 views

Can Spring LdapTemplate stream results?

I am trying to query an active directory for ALL person objects. There are over 700,000 results which are way too many to read into a List. My current solution is using paging to get all of the ...
12
votes
0answers
91 views

Can method result Java Streams be safely processed without isFinite() and isOrdered() methods?

There is the question on whether java methods should return Collections or Streams, in which Brian Goetz answers that even for finite sequences, Streams should usually be preferred. But it seems to ...
-4
votes
1answer
83 views

Stream#reduce results unexpected type, what am I doing wrong?

I have a simple Gradle project: plugins { id 'java' id 'application' } repositories { mavenCentral() } sourceCompatibility = '11' targetCompatibility = '11' mainClassName = 'demo.Main' ...
3
votes
3answers
83 views

Converting Stream<Stream<T>> to List<T>

I am new to java 8. I have written following piece of code: Stream<Stream<POLine>> list = poSearchResponseList.stream().map(poSearchResponse -> poSearchResponse....
2
votes
2answers
73 views

Java Unordered() function

In java 8, when I do, Type 1 list.stream().parallel().map(/**/).unordered().filter(/**/).collect(/**/); Type 2 list.stream().parallel().unordered().map(/**/).filter(/**/).collect(/**/); As both ...
-1
votes
1answer
50 views

Retrieve data from List<Map>

I subscribe to a topic using a Stream Stream<Map<String, Object>> sub = ipfs.pubsub.sub(topic) and after that I collect it to a List which will collect the first two results List<Map>...
-1
votes
2answers
32 views

Iterate and terminate in java 8 loop

Iterate in forEach loop/stream to check for non-null value and return the first non-null value of the item. List<Box> boxes; // Each box has List<Items> //Each item has a value Need to ...