Questions tagged [java-stream]

0

votes
2

answer
50

Views

Can we improve performance on lists other than java 8 parallel streams

I have to dump data from somewhere by calling rest API which returns List. First i have to get some List object from one rest api. Now used parallel stream and gone through each item with forEach. Now on for each element i have to call some other api to get the data which returns again list and save...
Pavan
1

votes
1

answer
2k

Views

Converting Map<String,String> to List<Object> in Java8 [duplicate]

This question already has an answer here: Java 8 stream Map to List 1 answer I have API which returns Map which needs convert into DTO. SubjectIdAndNameDTO (id, name constructor args) id name current implementation using traditional for loop and Map.EnterSet. How can i use feature of Java8 to simp...
Lakshman Miani
1

votes
1

answer
35

Views

IntelliJ hint while rounding BigDecimal division stream result

I have a little bit strange problem with IntelliJ hint while dividing result at the end of stream operation. products.stream() .filter( order -> order.getEstimatedRealizationDate().compareTo(begin) > 0 && order.getEstimatedRealizationDate().compareTo(end) < 0) .map(order -> order.getProduct().getP...
Martin
1

votes
3

answer
49

Views

Flatten a nested N-Level nested object in java

I have a java class class Example{ String field1; String field2; List subExamples; } In the above scenario, Example is having subExamples which is again a list of Examples. This nesting can be n-levels. What I want to achieve is to have a list of Examples, i.e to flatten the above object and col...
codeluv
1

votes
2

answer
74

Views

Java 8 expression fill list from list with another list inside

I'm trying to reach a lambda expression avoiding doing this: for (OrderEntity o: onEntryL) { for(GeoFenceEventEntity g: o.getGeoFenceEvent()){ if(null != g.getEndAt() && g.getDynamoGeofenceType().equalsIgnoreCase('WAREHOUSE')){ //all of them, get data } } } And on Lambda trying something like this (...
Elí Giacomelli
1

votes
3

answer
111

Views

How to convert the following code to Java 8 streams and lambdas

I have a complicated requirement where a list records has comments in it. We have a functionality of reporting where each and every change should be logged and reported. Hence as per our design, we create a whole new record even if a single field has been updated. Now we wanted to get history of co...
diwakarb
1

votes
3

answer
54

Views

Java 8 grouping function to return Map<String, Integer> instead of Map<String,Long>

I am using the below mentioned code to find number of Times each word as occurred in a String. Map map = Arrays.asList(text.split('\\s+')).stream().collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collectors.counting())) this code returns Map I want to transform this code to retu...
Lucie
1

votes
1

answer
32

Views

Extract a fields data from a Map<Integer, Object> into a String

I have an Customer Object like below. public class Custoemr { private String Id; Private String Name; Private String Address; Private String Description; Setter/Getter; toString; } This is Contained in Map map, which contains the customerId and Object as key and value respectively. For analysis purp...
Lucie
1

votes
1

answer
40

Views

Java Stream grouping and counting occuerences

I have a list of objects representing trades in a market. Each trade has an opening and closing time and a profit. I want to group them by a month and then count a number of trades with profit > 0 and < 0 in each month = create a Map with following structure {'MM' = {'Win' = numberOfWinTrades, 'Loss...
Spasitel
1

votes
2

answer
111

Views

Fibonacci using Stream And BinaryOperator in Java

I'm student and I learning functional Java 8. I got project to do and I don't understand how this function interface work. My teacher told me 'you should know that' and I'm looking for help to understand this problem. It should count Fibonacci series I got this code StreamUtils.generateRest(Stream.o...
anik
1

votes
2

answer
44

Views

Stream IllegalStateException

I am facing this error and have no idea how to debug it. The summary of the question is that I have to get the minimum and maximum of a stream. I cannot use Collections and the stream must be parallelizable. Furthermore, the stream is an argument so it cannot be duplicated. I am not asking for a sol...
Jayson
1

votes
1

answer
328

Views

Get String value if present or null if not present using Java8 Stream

I have a json similar like as shown below. The requirement is to get the key value based on the id. ie. lets say If Id is A1 key value should return 2gAwIBAgIQKGZsKfAUzaJHVantyrwVdzANBgkqhkiG9w0BAQs. The key array will always conatins only one element. { 'keys': [ { 'id': 'A1', 'key': [ '2gAwIBAgIQ...
Alex Man
1

votes
3

answer
80

Views

How to place duplicate elements from a list into an array?

I need to find duplicate items in the collection and put them in an array. I wrote this method: String[] mass = new String[(int) limit]; for (int i = 0; i < duplicates.size(); i++){ for (int j = 1; j < duplicates.size(); j++){ if (i != j && duplicates.get(i).equalsIgnoreCase(duplicates.get(j))){ mas...
Mefisto_Fell
1

votes
2

answer
64

Views

Iterating LinkedList using streams is altering result list due to RaceCondtion

We are iterating the LinkedList using Streams in java8, and creating another list. But due the race condition the result List size got alatered. List InfoList = new LinkedList(); documentList.stream() .parallel() .forEach(document -> { Info descriptiveInfo = objectFactory.createDescriptiveInfo(); Li...
Raghavan
1

votes
4

answer
98

Views

group by a field in Java Streams

So, I have an input JSON that looks like this: [{ 'added': '2014-02-01T09:13:00Z', 'author': { 'id': '1', 'name': 'George R R Martin', 'added_on': '2013-02-01T09:13:00Z' }, 'book': { 'id': '12', 'name': 'Game of Thrones', 'genre': 'Fantasy Fiction' } }, { 'added': '2015-02-01T09:13:00Z', 'author':...
nirvair
1

votes
2

answer
99

Views

Java Optional: flatmap and orElseGet [duplicate]

This question already has an answer here: Get value from one Optional or another 4 answers Optional orElse Optional in Java 6 answers I've coded that: Optional.ofNullable(this.cache.get(id)) .orElseGet(this.referenceService.get(id)); The problem is that this.referenceService.get returns an Optiona...
Jordi
1

votes
1

answer
56

Views

Java 8 nested list as singleton list in parent

public class Parent { String name; List children; } public class Child { String childName; } I have these 2 classes by which my data set becomes as below: List parents = new ArrayList(); List _child1 = new ArrayList(); _child1.add(new B('p1c1')); _child1.add(new B('p1c2')); _child1.add(new B('p1c3')...
gaurav arora
1

votes
3

answer
55

Views

Convert List<HashMap<String, Object>> to stream

I have a list of this type List ResultSet that contains the result of a query to a database. I wanted call stream() on the List object. How do I do that ? This code create my list: public class ResultSetToMap { int Columns = 0; List data = new ArrayList(); HashMap row = new HashMap(); public List R...
programmer
1

votes
1

answer
227

Views

Inclusive takeWhile() for Streams

I want to know if there is a way to add the last element of the stream that was tested against the condition of the method takeWhile(). I believe I want to achieve something similar to RxJava's takeUntil() method. I'm guessing there is no direct way to do this (correct me if I am mistaken), but I wo...
HiGuys
1

votes
2

answer
284

Views

Cannot resolve method stream() issue

I am currently learning about streams in java, but when i try to write some simple code like this Map map = new TreeMap(); map.put('Tom', 5); map.put('Andrew', 6); map.put('Kim', 3); map.put('Milo', 2); map.stream(); it gives me java cannot resolve method stream() I am using Inttelij and coding in...
sadurator
1

votes
1

answer
339

Views

NullPointerException when switch from stream to parallelStream

Help me understand this; I have a stream based logic that groups entities into a map-of-lists based on some key string that is constructed out of its fields. Using stream this runs without any error: Map mapOfkeyToListOfEntities = baseJournalEntries .stream() .collect(Collectors.groupingBy(eneity ->...
tbeernot
1

votes
1

answer
220

Views

java collect streams and grouping depending on variable

I was given these two classes 'Transaction' that has attributes Trader trader, int year, int value, long seq, and 'Trader' that has attributes String name, String city. I need to group this stream and sum only if seq = seq + 1: Trader raoul = new Trader('Raoul', 'Cambridge'); Trader mario = new Trad...
K. H.
1

votes
1

answer
97

Views

How to check an element is instanceof a class in Java? [duplicate]

This question already has an answer here: Is there something like instanceOf(Class c) in Java? 7 answers If I have three Classes (Foo, Bar and FooBar), how can I check for instance inside a Stream in Java 8? Is there anything like: Foo foo = new Foo(); if (Stream.of(Foo.class, Bar.class, FooBar.cla...
J. Doe
1

votes
1

answer
185

Views

Java stream doesn't recognise type

((JSONArray) JsonUtils.parseStringToJsonObject(response.getResponseBody()).get('firstArray')).stream() .map(s->((JSONArray) s).get(1).toString()).collect(Collectors.toList()) Why is this code snippet will return an Object and not a List? (response type is a IHttpResponse)
Twi
1

votes
3

answer
655

Views

How to apply Consumer with a map in Java?

I have created a Consumer which takes a string and makes it uppercase. I am trying to implement it along with a map to make all the strings in a list to uppercase. I understand that this can be done easily using String::toUpperCase but I am trying to do it with a Consumer and I am getting the follow...
Varun Upadhyay
1

votes
0

answer
402

Views

Stream on Iterable in Spring data jpa transactional

I am using Java StreamSupport to stream on Iterable return from repository method inside of @Transactional method in service layer. Svc: @Transactional(readOnly = true) public Map getAllProjects() { return StreamSupport.stream(projectRepo.findAllByOrderByNameAsc().spliterator(), true) .collect( Lin...
Pat
1

votes
1

answer
249

Views

How comparison between two list using streams? [duplicate]

This question already has an answer here: How to compare two Streams in Java 8 4 answers I have first list contains list of objects Users, List resultUesrList=array.stream().map(result>parseObject(result)).collect(Collectors.toList()); each object from list user contains list ranges: //Retrieve use...
user4343
1

votes
1

answer
147

Views

Performance Issue when using Java 8 Stream (Bulk of Data in a List)

I have the following 2 codes/logics in a single method: Code 1: Returns around 10K++ of data //myObjectRepository extends the spring CrudRepository (hibernate) final List myObjectList = myObjectRepository.getObjectsByIdAndReportDate(); Code 2: Filters the 10k++ of data //Only return valid objects fi...
Jown
1

votes
1

answer
403

Views

Java 8 streams.reduce() with combiner

My question is that i would like a breakdown of the following code I have a map and i want to replace certain strings with the map's value with the following reduce() function: Map environmentMap = new HashMap(); Function replaceFunction = environmentMap.entrySet() .stream() .reduce (Function.identi...
Karl Alexander
1

votes
0

answer
41

Views

return Stream values from a source of data in java function

Suppose data are written in Kafka. I want to write a function to return a Stream of unbounded values in Kafka. The following is the template of my function: public static Stream getData(String topic, int from){ // some kafka configurations consumer.subscribe(topic, listener); ConsumerRecords records...
1

votes
1

answer
142

Views

Java 8 Stream API - convert for loop over map & list iterator inside it

In the below code, I am trying to calculate the total price of a basket, where basket is a HashMap containing the products as key and the quantity as value. Promotions are available as a list of Promotion. I am looping over every map entry and for each of them iterating the promotions. If the promot...
josephine preethi
1

votes
0

answer
740

Views

Java 8 stream on untyped Vector [duplicate]

This question already has an answer here: Combining Raw Types and Generic Methods 5 answers Why does a Java generic raw class erase all generics to object when type parameters are unspecified? [duplicate] 1 answer Why won't this generic java code compile? 4 answers Why does this java 8 stream ope...
maestro
1

votes
0

answer
60

Views

Eclipse: Generic Predicates Compilation Error

I have this code: public Argument0 onlyIf(Predicate predicate) { return new Argument0(context -> elements.apply(context) .map(node -> Pair.of(node, context)) .filter(predicate) .map(Pair::getLeft)); } Eclipse is giving me this error exactly in '.filter' method call: See image As you can see the err...
Roberto Salazar
1

votes
1

answer
185

Views

Alternatives to catch/rethrow when using Java Lambdas?

I have encountered and contributed to projects which use Java8 streams and lambdas extensively. The code is littered with blocks like this: ... some other code ... -> { try { ... some more code ... } catch(SomeException e) { throw new RuntimeException(e); } } ... or alternatively private void someM...
Alex R
1

votes
1

answer
196

Views

Filter search Java 8 streams

I am trying to write filter function with Java 8 streams to filter by multiple paramaeters. createdFrom - Date (mm-dd-yyyy) // if null, filter without createddate From createdTo - Date - (mm-dd-yyyy) // if null, filter without createddate to CreatedBy - String //if null, filter without createdby Int...
RamKumar
1

votes
3

answer
633

Views

Multiple input parameters to Map function Java 8

File inputF = new File('C:\\sample.csv'); //Line 1 InputStream inputFS = new FileInputStream(inputF); //Line2 BufferedReader br = new BufferedReader(new InputStreamReader(inputFS)); // Line3 inputList = br.lines().skip(1).map(createObject).collect(Collectors.toList()); // Line 4 Function createobjec...
Neha
1

votes
1

answer
328

Views

Fork Join pool hangs

The case is that an application hangs infinitely from time to time. Seems that the bug sits in the following snippet: ForkJoinPool pool = new ForkJoinPool(1); // parallelism = 1 List entries = ...; pool.submit(() -> { entries.stream().parallel().forEach(entry -> { // An I/O op. ... }); }).get(); Th...
Aliaxander
1

votes
1

answer
166

Views

Configure threads in ParallelStream

I have below code public void addNames(){ List names = new ArrayList names.parallelStream().foreach(name->add(name)); } private void add(String name){ SQLSession session = SQLSessionFactory.getSession(config); Connection con=Session.openConnection(); con.insert(name); con.commit; con.close } The pro...
Raj
1

votes
0

answer
366

Views

Hibernate query cache with Spring Data JPA and Stream is not working

I'm using Hibernate query cache on my Spring Data JPA repository, and all works if I use List as return type, if I use Stream seems that hibernate not cache results: Not working code: @Query('select E from Entity E where E.id = :id E.name asc') @QueryHints({@QueryHint(name = 'org.hibernate.cacheable...
ccardone
1

votes
2

answer
92

Views

Filter a Map by values in Java?

I have a map where the values are GregorianCalendar/String and the keys are Reminder/Contact: private final Map elements = new HashMap(); Another list: List result = new ArrayList I would like to filter a map and create a list by reminder themes. public class Reminder { String name; String theme;...
7Bliz

View additional questions