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.
11,394
questions
0
votes
1
answer
21
views
Group list of objects into Map<String, Boolean> with value being true if any object in group has field set as true using Java stream API
In a Java 17 project, I have a collection of objects with a String field propGroupName representing the group this object belongs to and a Boolean field propValActive representing whether this object ...
-1
votes
1
answer
59
views
Is there performance impact of using `map() + stream()` vs `flatMapMany() + map()`?
Is there difference in performance between using map() + stream() and flatMapMany() + map()?
For example, we have a collection of some entities and we need to map it to another representation of these ...
0
votes
2
answers
46
views
Issue with sorting and creating map using java8
i have a code like these
@Data
public class person{
String firstName;
String lastName;
int orderNum;
}
List<person> personList = new ArrayList<person>();
i am trying to sort object ...
0
votes
1
answer
30
views
How to return child enity along with its parent entity details in springboot
I want to get Loans details along with each loan Parent details, but i am geting only Child details not parent details.
Loan is the child entity, and User is the Parent Entity
Pageable pageable = ...
1
vote
2
answers
85
views
Populating an existing Set<String> via Java 8 streams
I am new to Java streams and functional programming and I wonder if my question will ever even have a valid use case or it is just not meaningful.
I have the following code that gives me a Set from an ...
-2
votes
1
answer
28
views
How can I calculate the average line length of a file with only one sequence of stream operations? [closed]
My task is the following:
Write a method, that calculates the average length of the lines in a file. (It should return if there is no line in the file.) The declaration should be
static double ...
0
votes
3
answers
47
views
How to group a list of objects into a Map of Map based on object's attributes in Java?
I have a list of objects that I want to convert to a map of maps.
class A {
String aProp;
String bProp;
String cProp;
}
then I have List<A> aList.
and I am trying to convert them into a ...
-2
votes
1
answer
73
views
Convert List to Map of Map
I have an object array like below.
[
{
"defName": "Project",
"defDesc": "Project 1",
"defID": "abcd123",
...
0
votes
2
answers
117
views
read all files and write their contents into one file [closed]
How do I read all the files and write their contents into one file?
Is it possible to do this using Files.walk?
Path pathDir = Path.of("files_STREAM_Lesson7");
if (!Files.exists(pathDir))...
1
vote
1
answer
41
views
Java8-stream complex groupingBy
I want to do groupingBy and create a map that return me <Integer, List<Long>>
my model is as below
public class Partition {
private String tableName;
private int vendorKey;
...
0
votes
2
answers
36
views
Comparing and extracting changes between two similar Excel files, but with different row order
I'm a beginner in Java and I have a problem.
I have two excels that I need to compare and extract the changes. Excels are practically the same but differ in row order (example below). How to extract ...
-2
votes
1
answer
57
views
What is the Big-O time complexity of Java's Stream.max()?
There are lots of questions about Big-O complexity of Java's Stream, Stream.sorted(), etc. But I haven't found one from Java's Stream.max().
It doesn't seem to have been answered on StackOverflow. I ...
0
votes
1
answer
47
views
How to convert Json Object to array of json objects
Below is my input
nameJson : {"english":"tom","dutch":"john","spanish":"sam"}
sectionJson: {"english":"A","dutch&...
0
votes
1
answer
44
views
How to optymalize iteration by list and calling method
I would like to optymalize my process of iteration by list and filltering it.
For example:
I have a short list of some similar objects where the difference will be one field:
List<ObjTest> ...
0
votes
3
answers
65
views
How to stream a map with a values Stream<String> using Stream API?
I have the map Map<String, Stream<String>>. I need to build sorted stream of all participants without duplication, ignore null or empty strings, trim extra spaces and modify each to Title ...
0
votes
2
answers
56
views
Streams-peculiar order of operation between intermediate and terminal operation
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Stream.of(1, 2, 3).map(i -> {
System.out.println(i+":inside map");
...
4
votes
3
answers
122
views
Why doesn't the count() terminal operation print the intermediate steps? [duplicate]
As simple as:
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Long x = Stream.of(1, 2, 3).map(i -> {
System.out.println(i);
return i + ...
0
votes
3
answers
65
views
using collection and if else statement in java in optimize way
I have a below code which is working as expected and I want to optimize it, possibly if using methods of stream.
List<List<String>> colorsList = List.of(
List.of("red","...
0
votes
1
answer
76
views
How to write lambda streams function to work with jsonobject with different keys and json array
I'm very new to Java 8 lambdas... I want to write a lambda function that takes a JSONArray, goes over its JSONObjects and creates a Json object of certain field.
For example, a function that takes the ...
-1
votes
0
answers
45
views
Unable to obtain LocalDateTime from TemporalAccessor: when trying to sort the date in the stream
I want to sort the posts by date("hh:mm:ss"). but I get a mistake. Can you tell me what I did wrong?
java.time.format.DateTimeParseException: Text '12:55:36' could not be
parsed: Unable to ...
0
votes
2
answers
117
views
Sorting an int Array using Java Streams
I am trying to get familiar with Java streams and similar things around that area, but unable to sort an array of type int. Here is my code, which does not sort the array at all.
class Scratch {
...
1
vote
3
answers
77
views
Map<String, Long> to Map<String, Boolean> if long is > X with Stream
I am looking for a Stream Function to get a Map<String, Boolean> from Map<String, Long>. if the Long is greater than value X, it should be true, otherwise false. Long acts as counter in ...
0
votes
1
answer
48
views
parse the array from file
I have a problem when reading an array from a file. how can this be done in a stream? I need to count the whole string and put it in the Student fields
// # Name Surname Marks
// 1 Mike Scott [4,5,5]
/...
0
votes
0
answers
32
views
read part(array) of the file using stream [duplicate]
how can an array be read from a file? I have a Student class, I need to fill in its fields, the "marks" field is an array, I'm trying to fill it in. I need to do it in the stream.
maybe ...
0
votes
1
answer
51
views
Can't get reducer stream to work in Java. What's wrong with my code?
I want to use a reducer to sum up all the inputs from 'args', then divide by the args length to get the result I'm looking for (just a simple function to learn java).
I'm following (as far as I can ...
0
votes
0
answers
41
views
Determine a winner based on a single random value and an array of probabilities using java streams
I have an array of probability values that add up to 1.0. I want to determine one winner element based on a random number between 0 and 1:
double probabilities[] = {.2, .75, .05};
double randomValue =...
-1
votes
1
answer
96
views
read part of the file using stream
How can an array be read from a file? I have a Student class and I need to fill in its fields where the marks field is an array. I'm trying to fill it in. I need to do it using the stream API. Maybe ...
-2
votes
0
answers
13
views
How to stream below list of json
I have below response, I want to retrieve "enabled" attribute value from json response using stream. Condition is that, if merchantRef has value need to retrieve that enabled value.
"...
0
votes
3
answers
67
views
Map<String, Map<String, Double>> streamapi [duplicate]
I can't understand why my code doesn't work. Tell me, if it's not difficult, I really ask.
error in the stream, but I can't figure out why I can't fill Map from List
I want to know what is the student'...
0
votes
1
answer
42
views
How to filter using streams when we have multiple for loop and collect list out of filtered items from second list stream
I am trying to change the set of code for normal forEach loops to stream and filters. But finding errors in the way it's getting implemented.
Current Code:
List<Long> validFromPersonIds;
List<...
0
votes
4
answers
100
views
Java Stream collectors: how to create total with counting
I have a list of objects of class Result defined as:
class Result {
String code;
String description;
Duration value;
}
and these two classes:
class Product {
String code;
String ...
0
votes
1
answer
40
views
Read if string.startsWith() and stop the stream if the condition fails
I get message with message-headers. See sample message below
private static String sampleMessage() {
return """
message from arunmantics.com
X-...
0
votes
1
answer
35
views
Where is the implementation of abstract forEach() of Stream interface?
Iterable forEach():[No Confusion]
As I know that forEach() is a default method and defined inside Iterable Interface.
default void forEach(Consumer<? super T> action) {
Objects....
1
vote
2
answers
49
views
How to return a value based on a property of a list of objects using streams
I need to return the name (String) of the Person record with shortest height using streams.
I have searched online but all i could find that kind of worked was finding the actual lowest int value, not ...
0
votes
2
answers
73
views
Java streams and lazy collections
I have a method which returns a Collection of objects by performing some costly operation (e.g. using a database for resolving objects by ther ID).
Let's use this method as an example:
public static ...
0
votes
1
answer
46
views
How to control the when calling parallelStream
I have following simple code to demonstrate the usage of parallelStream,
int reducedParallel = Arrays.asList(1, 2, 3).parallelStream()
.reduce(10, (a, b) -> a + b, (a, b) -> {
System....
0
votes
2
answers
40
views
How can i get access to elements of string array inside of a stream?
I need to count and sort hashtags inside string using stream api.
example:
String posts = "Example #java #streams string etc."
I've tried to split this string to String[] and then iterate ...
0
votes
3
answers
63
views
How to replace if-Statement by using Optional/Stream API
Is there a way to replace the if statement by using Optional or similar lambda construct?
The idea is to having one statement without if.
private boolean check(@Nullable Result result) {
if (...
-2
votes
1
answer
59
views
find the sum in the stream [closed]
I found the average value for each student's subject. I need to calculate the sum of all student averages. for example, for Anna Math(0.5)+History(2.0)+Physics(3.3)=5.8
put in Map<String,Double> ...
-3
votes
1
answer
36
views
the task for the stream. put in Map [closed]
I need to add up all the averages for each subject. As a result, I want to find out which subject is the easiest. I add up all the average values in physics , mathematics, History and as a result I ...
-1
votes
1
answer
53
views
Issue with Java IntStream whilst trying to solve a codewars problem (Prime Streaming PG-13) [duplicate]
I signed up on codewars in March and I have finished a number of challenges. I am encountering difficulty with the following. The name is Prime Streaming (PG-13) and is highlighted below.
Create an ...
0
votes
1
answer
49
views
Convert List<Integer> into Map<Integer, V> using streams
I am new to Java 8, I want to print Square of even number from the list and print the result in key value pair, where Key is the even number from the List and value is square of that number.
public ...
-2
votes
3
answers
64
views
how to put one of the values in a stream in a String [closed]
I have an int type number. If the number is 0, then put "bad" in the String, If the number is 1, then put "normal" in the String, If the number is 2, then put "good" in ...
0
votes
1
answer
69
views
Java parallel task execution [closed]
I have 1000 products which needs to executed in parallel and result of the output is also a collection. I need to maintain the order, so I used parallelStream() with forEachOrderedlike below
products....
0
votes
1
answer
107
views
Ignoring 0 score tasks using Stream API
I have 2 methods and I need to count average values including tasks that a student did not try to solve (with 0 score). Everything works until 0 appears. And I stuck with this. What is my problem?
...
3
votes
4
answers
79
views
Filtering data based on two conditions in java streams
I have the following code
public class Car {
Long carNum;
String carEngine;
}
The data in List object is as follows:
Car(carNum=1, carEngine=S02K),
Car(carNum=1, carEngine=null),
Car(carNum=...
-2
votes
1
answer
28
views
Libraries for processing multiple Streams
I need advice on building an application that will:
connect to a stream of Content-Type: text/event-stream
there can be 1+ streams (all streams have the same data model)
aggregate incoming messages ...
0
votes
2
answers
66
views
I can't apply the average() method in the stream
I need to find the average of all the student's subjects. the result should be similar to this
Ann 3.5
Kate 4.0
for each student, all his grades in all subjects are added up.
my solution doesn't work, ...
0
votes
2
answers
69
views
how to get a LinkedHashMap from the list using stream api
I need to grouped the list by position and sorted by age and into a LinkedHashMap.
If I put it into a HashMap, the result will not be sorted. I can't figure out how to create LinkedHashMap<String, ...
0
votes
1
answer
47
views
Why my java compiler think the initialized array is an ArrayList?
I'm using stream reduce in Java and I wrote this code:
ArrayList<CacheElement>[] initialArrayList = initArrayWithArrayList(newCacheCapacity);
Arrays.stream(cache).reduce(...