Questions tagged [java-8]

10447 questions
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
3

answer
185

Views

How to insert 780k records Spring Data Postgres

CSV file will be uploaded in Amazon S3 bucket. Current Implementation: Reading CSV file using OpenCSV utility's readAll which returns List Map every column value to an entity object Create a List object (Current Size :: 15000) Invoke Spring Data CRUD Repository saveAll(List objects) Out of 780k reco...
Phaneendra
1

votes
1

answer
26

Views

Java 8 wildcard type cannot be instantiated directly

Java 8 here. I have the following generic class: public class Memory { private String moniker; private Date timestamp; private T data; // constructors, getters & setters, etc. } I'm trying to build a non-generic MemoryFactory like so: public class MemoryFactory { public Memory createMemory(Object da...
hotmeatballsoup
1

votes
1

answer
47

Views

How to invoke a generic function inside another function with a timeout with java 8?

I have a function that gives me a state of service: public ServiceState getServiceState(){ return someService().getState(); //currently state return 'NOTACTIVE' } And when I invoke a certain method on the system, the service should be in active state after x amount of time (unknown time): someServi...
totothegreat
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
1

answer
58

Views

Java 8 Iterate over Map.Entry and create and return List of new Object

How can I achieve the logic below using java8? List r = searchAttributes.rowMap().forEach((id, value) -> { new GenericKeyValueHolder(id, value); });
Jigar Naik
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
21

Views

Getting the capture of a generic object instance in Java

Java 8 here. I have the following POJOs: public class Fizz { // ctor, getters & setters, etc. } public class Buzz { // ctor, getters & setters, etc. } public class Foobar { // ctor, getters & setters, etc. } public class Envelope { private String name; private PAYLOAD_TYPE payload; // ctor, getters...
hotmeatballsoup
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
25

Views

Simple JSON value parsing for Java 8

Java 8 here though I have Jackson and Jettison on my classpath already (as dependencies). I am being given the following string of JSON (as an example): { 'widgets': { 'email': '[email protected]', 'maxSize': 50 }, 'environments': { 'LOCAL': { 'maxSize': '40' }, 'DEV': { 'maxSize': '100' } }, 'fru...
hotmeatballsoup
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
1

answer
36

Views

Ambiguous call to Module

I am trying to recompile a JAVA8 code in JAVA11. Getting below compilation errors. error: reference to Module is ambiguous private Module module; both interface com.module.Module in com.module and class java.lang.Module in java.lang match Being new to the Java not able to fully understand the root...
AKJ
4

votes
2

answer
123

Views

Jaxb unmarshal xml which contains the & <> signs

To parse my XML with JAXB I have already generated the required POJO's and successfully able to parse the XML. But whenever my xml contains '&' '' signs it's failing. As per the rule this needs to be changed to '&' but the 3PP generating the XML does not follow the rule. Now how can I parse this...
Souvik
0

votes
0

answer
2

Views

Combine Consumers with different arguments or different arguments number

Let's say, our method receives input String and returns some List output. This output is the result of some number of generators, some of which depend on input and some of them not - they just add predefined values. I want to implement these generators like a list of some function interfaces (Consu...
Aleksey Balenko
0

votes
2

answer
28

Views

Efficient Java construct for Arraylist Processing and calling different methods

Please, Is there an elegant and efficient way of doing the following in Post Java 8 i.e. 1. Looping through an arraylist 2. Reading the object 3. Calling different methods of potentially different objects using the values contained in the arraylist items I did look at streams, switch statement, but...
olatom
1

votes
2

answer
1.9k

Views

Create lazy messages in log4j2

I have this code: import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Test { private static final Logger logger = LogManager.getLogger(); public static void main (String[] args) { logger.info('Text: {}', getText()); } static String getText() { // Expensiv...
Olivier Grégoire
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
2

answer
125

Views

Optional Of Nullable Executes orElse when map returns null

I have written a simple snippet String aa = 'aa'; String aaa = null; String result = Optional.ofNullable(aa) .map(s -> aaa) .orElse('bb'); System.out.println(result); orElse shall be executed when aa is null. But it is getting executed when map returns null as well. My understanding is that orElse...
Patan
1

votes
1

answer
142

Views

Writing unit tests for Java 8 streams

I have a list and I'm streaming this list to get some filtered data as: List submittedRequestList = list.stream().filter(Objects::nonNull) .map(config -> taskExecutorService.submit(() -> requestHandler .handle(jobId, config))).collect(Collectors.toList()); When I wrote tests, I tried to return some...
codebot
1

votes
2

answer
104

Views

Singleton Database Class for JDBC Pool using Apache Tomcat JDBC

I am trying to configure a singleton database class to allow connection pooling against Oracle XE 18c database using JDK8 and Tomcat7. I can not compile the source because of the following error: unreported exception SQLException; must be caught or declared to be thrown Class source code: package co...
M.E.
1

votes
1

answer
114

Views

Is ArrayList.forEach() a mutative operation?

I have a HashMap groups which maps to ArrayList objects for its values. I wanted to re-assign the values given they meet a particular condition (i.e. in this case, they are present in another list) and came across the forEach method. Here's how I implemented it. I could not find any documentation as...
Garikai
1

votes
1

answer
63

Views

How to unit test CompletableFuture.thenAccept() by avoiding manual sleep

How to avoid manual sleep in unit test. Suppose In below code the Process and notify takes around 5 seconds for processing. So in order to complete the processing, i have added sleep of 5 seconds. public class ClassToTest { public ProcessService processService; public NotificationService notificat...
Niraj Sonawane
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
1

answer
93

Views

Default Java on Windows machine

I have a Windows 10 x64 machine. I had Open JDK 10. My JAVA_HOME points to Open JDK 10 location. My Path variable has %JAVA_HOME%/bin; part. Then I installed Java 8. https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html Java installer changes Path. C:\Users\user>set P...
Yan Khonski
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
3

answer
41

Views

Best way to find uncommon elements inside list [duplicate]

This question already has an answer here: returning difference between two lists in java 7 answers I am having lists of String type say list aLista and bListb first list might have at max 10 elements however bListb might have thousand or even more elements. Now i have to find all elements from aLis...
Sunil Goyal
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
2

answer
55

Views

Process flow of a Closure example | Java 8

Was going through a closure example for the first time , but I'm having a hard time wrapping my head around the control flow. public class TestLambdaClosure { public static void main(String[] args) { int a= 10; int b=20; //doProcess(a, i-> System.out.println(i+b)); doProcess(a, new Process() { @Over...
Soumava Das
1

votes
1

answer
31

Views

How to get page size of a pdf bytearray with plain java code?

I have a bytearray of a pdf document. Is it possible(without using any external libraries) to get to know how many pages the pdf contains? Is it possible with only the use of java8? I find it rather stupid that I have to import a whole pdf external library in my project for just getting to know the...
Bladerunner
1

votes
1

answer
19

Views

Accepting formatted Json (multi-line) input from user in a Java console app with Scanner (all lines not being read)

I have a scenario where I need to take formatted Json (multi-line) as an input and do something with it. I figured doing it in a simple console app would be good since it is just a tool I am creating and want it to be able to be ran locally. If I should be reading the Json from a file instead please...
Blake Rivell
-1

votes
2

answer
38

Views

Why does Java's Optional.of() won't accept null values? It's not really an “optional” value anymore then [duplicate]

This question already has an answer here: Why use Optional.of over Optional.ofNullable? 4 answers Is there a real reason to use Optional.of()? 8 answers I know we have Optional.ofNullable() if the value can also be null. My question is, why isn't that the default behaviour for Optional.of() as wel...
Zoltán Umlauf
1

votes
2

answer
79

Views

How to discover what the missing progressive arithmetic number missing in the List<Integer> is in Java 8?

I have a huge list of numbers in a sequence but one number is missing. How can I find out what the gap number missing is with efficiency using Java 8+? I did just like this: public class PAMissingNumber { public static void main(String[] args) { List listInteger = Arrays.asList(1, 2, 3, 4, 6, 7, 8,...
Alexandre Barbosa
1

votes
2

answer
51

Views

Use method reference to check boolean value match instead of lambda

Use of Method reference for comparing boolean. Instead of (t->t), I want to use method reference. Method reference is applicable for non-boolean value match as stated below. Full Code: public class AccountListTest { public static void main(String[] args){ List list = new ArrayList(); Account a1 = n...
S Kumar
1

votes
3

answer
152

Views

String manipulation in Java8

I have written some code in Java7 to manipulate a String. If the string size is >= 10 it will return a substring of size 10 but if the size is < 10 it will append 0s in the string. I wonder if there is a way to write the same code in Java8 using streams and lambdas. There are some question related t...
Johan
1

votes
1

answer
19

Views

Spanish language encoding issue with Java Properties class load method

I am trying to encode the Spanish language for internationalization and use the Java Properties class load method to populate it to pass it to frontend. I have tried to encode it using UTF-8 but still the accent characters are not coming correctly. import java.io.ByteArrayInputStream; import java....
user11391059
4

votes
0

answer
101

Views

Implementing Nashorn ClassFilter equivalent

Using the nashorn library jdk.nashorn.api.scripting.* one can implement the ClassFilter interface to disable instantiating any class from within a javascript run in Java: private static class NoJavaFilter implements ClassFilter { @Override public boolean exposeToScripts(String s) { return false; } }...
ps0604
1

votes
1

answer
20

Views

Modify text of data member of objects inside a list

What's the best way of replacing space with dashes '-' inside a list that contains POJO objects? Below is the class public class State implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String stateCode; private String stateName; public State() { } pu...
Arya

View additional questions