FAQ Database Discussion Community


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...

Java label irregularity (possible bug?)

java,label,java-8,standards
If we look at the Java standard §14.7, we see that statements may have label prefixes, e.g.: LabeledStatement:      Identifier : Statement In theory, a label should be able to label any succeeding statement. So, for example, the following compiles accordingly: public class Test { public static void main(String[] args) {...

Create Multimap from Map> with key as V[0] and value as K using Java 8

java-8,guava
I have a Map<String,List<String>>(say inputMap) and I want to convert this to another Map<String,List<String>> where each (k,v) in the new map is (v.get(0),k) of inputMap. Ex. X -> B,C,D Y -> B,D,E Z -> B,G,H P -> A,B,D Q -> A,D,F R -> A,C,B to B->X,Y,Z A->P,Q,R I initially thought...

operators in predicate as argument in lambda expression

java,lambda,type-conversion,java-8,predicate
I need to use Predicate as argument in lambda expression. I tried an example code but seeing compiler error. I see that the compiler is treating the same Predicate differently for different arguments. So Predicate arguments n -> true and n -> false works but n -> n%4 == 0...

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) ->...

Play! Framework support for Java 8 Optional

java,playframework,playframework-2.0,java-8
I've got a Play! 2 routes file and controller that looks something like this: GET /books BooksController.getBooks(author: play.libs.F.Option[String]) public class BooksController extends Controller { public static Result getBooks(play.libs.F.Option<String> author) { ... } } I would like to refactor it to use Java 8's Optional, but this causes a compilation error:...

Spring Integration - @Filter discardChannel and/or throwExceptionOnRejection being ignored?

java-8,spring-integration
I have a java DSL based spring integration (spring-integration-java-dsl:1.0.1.RELEASE) flow which puts messages through a Filter to filter out certain messages. The Filter component works okay in terms of filtering out unwanted messages. Now, I would like to set either a discardChannel="discard.ch" but, when I set the discard channel, the...

JavaFX Tableview not populating data to column

javafx,java-8,javafx-8
I am trying to create a TableView with 1 counter + 4 value columns. But for some unknown reason, columns val3, val4 are not getting populated in the tableview. I have updated the getVal2() method with "val3.get()", and I could see the val3 value in column of Value2. So, I...

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....

Java 8 Optional.ifPresent is my code wrong or is it eclipse?

eclipse,java-8,nullable,optional
I am new to Java 8 and trying out Null type annotations and Optional. For my example below, I have used String rather than my class and am calling toUpperCase just to call something, in my case I actually call a function passing in a parameter (so don't think I...

Passing method as a parameter - Is this possible?

java,java-8
I am trying to migrate to java 8 and have a number of methods in my dao classes which do the following @Override @SuppressWarnings("unchecked") public List<Group> getGroups() { Session session = sessionFactory.openSession(); List<Group> allGroups = (List<Group>)session.createQuery("from Group").list(); session.close(); return allGroups; } Here the same boiler plate sessionFactory.open and session.close is...

java 8 - some error with compiling lambda function

java-8
public class GrammarValidityTest { private String[] dataPaths = new String[] {"data/", "freebase/", "tables/", "regex/"}; @Test(groups = {"grammar"}) public void readGrammars() { try { List<String> successes = new ArrayList<>(), failures = new ArrayList<>(); for (String dataPath : dataPaths) { // Files.walk(Paths.get(dataPath)).forEach(filePath -> { try { if (filePath.toString().toLowerCase().endsWith(".grammar")) { Grammar test =...

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...

How to sort HashMap in java depending on the size of value List

java,java-8
I have a hashmap like the following HashMap<String, ArrayList<String>> map=new HashMap<String, ArrayList<String>>(); map.put("USA", Arrays.asList("CA","IA","IL")); map.put("India", Arrays.asList("MUM","CAL")); map.put("Canada", Arrays.asList("TOR")); I want to sort the map depending on the size of the list in the value in ascending order.How can i do that. Is there any nice method to do so?...

Is it possible to pass argument via method reference?

java,java-8,argument-passing,method-reference
I have the following code line: MyClass{ Runnable job; ... } and inside one of the method: this.job = myImporter::importProducts; Now importProducts is method without arguments: public void importProducts() { ... } But I need to add argument to this method now. After adding new argument, line: this.job = myImporter::importProducts;...

Java 8 way to repeat a block of code x times [duplicate]

java,java-8
This question already has an answer here: Does Java 8 provide a good way to repeat a value or function? 3 answers Maybe a normal for loop is still the right way but I wanted to see if there is a more succinct way to do it in java...

Maven error with Java 8

java,maven,java-8
Getting an error with Maven and Java 8 (jdk1.8.0_45). This issue does not occur with Java 7. MCVE Create a sample maven project. For example: mvn archetype:create -DgroupId=testinovke -DartifactId=testinvoke Create the following content in the generated App.java file package testinovke; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; public class App {...

How should I be using LambdaMetaFactory in my use case?

java,reflection,lambda,java-8
Despite having read all the documentation I'm aware of, I cannot resolve an issue with using lambdas to execute a method. To give a bit of background my use case is a plugin system. I'm using an annotation (@EventHandle) which can be assigned to any method. I use reflection and...

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?...

How to remove a collect into a new stream from the middle of a java 8 stream?

stream,java-8
I'm working on a Java 8 stream. And I need group by 2 keys in a map. And then put these keys with their value into a new function. Is there a way to skip the collector and reading it out again? graphs.stream() .map(AbstractBaseGraph::edgeSet) .flatMap(Collection::stream) .collect(Collectors.groupingBy( graph::getEdgeSource, Collectors.groupingBy( graph::getEdgeTarget, Collectors.counting()...

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) }, //...

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:...

Java byte array doesn't convert back to its original string when using DatatypeConverter

java,arrays,byte,java-8
I am using DatatypeConverter to convert my strings to byte arrays and vice-versa, however when going from a byte array back to a string it doesnt report the same value as initially given. This is a minimal example that runs on ideone /* package whatever; // don't place package name!...

Mapping a list to Map Java 8 stream and groupingBy

java,collections,lambda,java-8
I have this simple Bean class: public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } In...

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...

Java JDK 8 IndexedPropertyDescriptor has changed since JDK 7 with List object

java,java-8,java-7,introspection
I have a simple issue. I have a program working in Java JDK7 but it doesn't work in JDK8 because of some introspection changes. Here is a test program to reproduce the issue: import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.ArrayList; import java.util.List; public class Main { public...

Java constructor reference assignment Vs new created object assignment

java,constructor,java-8,variable-assignment,method-reference
I met in our project following code: MyInterface var = MyClass::new; Is there difference with MyInterface var = new MyClass(); Lazy?...

What is the difference between these constructs such that one won't compile?

java,lambda,compilation,java-8
A little backstory (ok, a lot): I've been working on creating classes that take java.util.function types and wrap their execution with try/catch blocks to remove the need for using try/catch from within lambda statements. Something that would allow this test code: list.forEach(ExceptionWrapper.wrapConsumer(s -> {throw new Exception(s);})); In doing so, I...

How to wrap a method that returns an optional with fromNullable?

java-8,guava,optional
I have a method that I don't own that is returning null but return type is Optional<Boolean>. When I call x.IsPresent() it throws (scenario #2). I tried wrapping the method in a fromNullable but I get a type mismatch (screen shot below). How can I fix so IsPresent() doesn't throw?...

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'...

Java 8 , JCE Unlimited Strength Policy and SSL Handshake over TLS

java,ssl,jvm,centos,java-8
With Java 8, server which only supports TLSv1, it fails to make secure socket connection from cent OS Version java version "1.8.0_45" Java(TM) SE Runtime Environment (build 1.8.0_45-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode) Source import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;...

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?

Why is generic of a return type erased when there is an unchecked conversion of a method parameter in Java 8?

java,generics,java-8
Consider the following code sample: import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List list = new ArrayList<Integer>(); String response = getProducer(list).get(); } static Producer<String> getProducer(List<Integer> list) { return new Producer<String>(); } } class Producer<T> { T get() { return null; } } When...

Java 8 - Difference between Optional.flatmap and Optional.map

java,java-8
What's the difference between these to methods: Optional.flatMap() and Optional.map()? An example would be appreciated....

Why did Java 8 introduce *Integer.sum(int a, int b)* [duplicate]

java,integer,java-8
This question already has an answer here: Purpose of Objects.isNull(…) / Objects.nonNull(…) 1 answer I just noticed that JDK8 introduced this method for Integer class: /** * Adds two integers together as per the + operator. * * @param a the first operand * @param b the second operand...

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%...

Convert time based on timezone using java.time

java,time,java-8,java-time
How to change the time based on timezone in LocalDateTime, here i have built a date with Time zone as EST, now i need to find the UTC of the corresponding time. please help me how to solve this String str = "16Jun2015_153556"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy_HHmmss"); formatter.withZone(ZoneId.of("EST5EDT")); LocalDateTime dateTime...

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...

Is it possible to truncate date to Month with Java 8?

java,java-8,truncate,java-time
I want to get the milliseconds truncated to days, I can use Instant.now().truncatedTo(ChronoUnit.DAYS).toEpochMilli() But I can't truncate to ChronoUnit.MONTH (it throws an exception). Do I need use a Calendar?...

Consult the code of Java SE 8 online? [closed]

java,java-8
I would like to consult the Java code for Java SE 8 online without downloading it all. Is this possible ? It may be simple question. ...

How can I suppress anonymous new runnable() can be replaced with lambda

java,android,lambda,java-8
I got "anonymous new runnable() can be replaced with lambda" warning with the following code. final ScrollView sv = (ScrollView) findViewById(R.id.scrollView); sv.post(new Runnable() { @Override public void run() { sv.fullScroll(ScrollView.FOCUS_DOWN); } }); I searched on Google very hard and seems to be re-write using lambda expression... final ScrollView sv =...

Ensure List of elements ordered by field in element

collections,java-8,guava,method-reference
Using Guava it is possible to ensure ascending ordering this way: import com.google.common.collect.Ordering; import io.predictor.dao.ohlcv.OhlcvHm; import static java.util.stream.Collectors.toList; assertThat("Ordered by age", Ordering.natural().isOrdered( employees.stream().map(Employee::getAge).collect(toList()))); It is strange for me that Guava (for all its close relation to Java lambdas) does not provide easy solution for such cases. Of course I can...

Tomcat failing to startup

java,tomcat,java-8,java-7
A few days ago when I turned the computer on, I tried to start up tomcat and got a surprise for the first time since I deal with software development. The exact error message is: Using CATALINA_BASE: "C:\apache-tomcat-8.0.9" Using CATALINA_HOME: "C:\apache-tomcat-8.0.9" Using CATALINA_TMPDIR: "C:\apache-tomcat-8.0.9\temp" Using JRE_HOME: "C:\Program Files\Java\jdk1.8.0_45" Using CLASSPATH:...

Eclipse Kepler is unable to set the Java jdk 1.8 when maven project is updated

java,maven,java-8,eclipse-kepler
Installed java version is 1.8, while selecting this version in pom.xml and updating the maven project,it automatically jumps from 1.8 to 1.4, due to which I am unable to have Lambda expression specific code. I am using eclipse kepler. Any idea what is happening here ?...

Split and Loop in java 8

java,split,java-8
I have this problem which I want to solve in java 8, I have a string which is concatenated by . A.B.C.D Number of characters in the string can vary. I have this method, which takes the string as input and number of level deep it has to go, I...

Java 8 : Lambda Function and Generic Wildcards

java,lambda,java-8
I have the following class class Book implement Borrowable { @Override public String toString(Function<? extends Borrowable , String> format) { return format.apply(this); } } This gives me an error that i cannot use "apply" on this(Book object). My current formatter is Function<Book, String> REGULAR_FORMAT = book -> "name='" + book.name...

Functional Interface Inheritance Quirk

java,lambda,java-8,default-method,functional-interface
I have a custom interface I've been using for some time that looks something like this: public interface Function<T, R> { R call(T input); } I'd like to retrofit this interface with both Java's Function as well as Guava's Function, while keeping it a FunctionalInterface. I thought I had the...

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...

Merging two List of objects in java 8

java,stream,java-8
Let's consider a java class Parent with Parent with 20 attributes (attrib1, attrib2 .. attrib20) and its corresponding getters and setters. List<Parent> list1 contains n Parent objects Parent objects. List<Parent> list2 contains n Parent objects Parent objects. Now I want to merge two list and avoid duplicate objects based on...

Java 8 parallelStream for concurrent Database / REST call

java,multithreading,concurrency,parallel-processing,java-8
Here I am using Javaparallel stream to iterate through a List and calling a REST call with each list element as input. I need to add all the results of the REST call to a collection for which I am using an ArrayList. The code given below is working fine...

Java 8 map to only value type collection

java,lambda,java-8,collectors
I want to convert my Map <K,V> into only a Set <V>. I could not find any example anywhere, including Oracle's documentation here: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html All I could go further is: myMap.entrySet().parallelStream(). filter((entry) -> entry.getKey().startsWith("a")) .collect(Collectors.toSet()); This returns a Set of Map.Entry. In this example it's Map<String, String> so I would...

Take out the hour, min and second in new Date/Time in Java 8

java,java-8,localtime
I looked at the new Date/Time in Java 8 and saw that they made it much easier than before. So I thought of a thing to do with this new Date/Time and see if I could do it. I want to give the program two different time and let the...

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?

Lambda Metafactory Variable Capture

java,lambda,java-8
When creating a lambda manually using MethodHandles.Lookup, MethodHandles, MethodTypes, etc, how might one implement variable capture? For example, with no capture: public IntSupplier foo() { return this::fortyTwo; } /** * Would not normally be virtual, but oh well. */ public int fortyTwo() { return 42; } and its clunkier form,...

Spring Integration Java DSL - @ServiceActivator method with @Header parameter annotations

java-8,spring-integration
I have a Spring Integration 4 bean method with the following signature: @Component public class AService { @ServiceActivator public Message<?> serviceMethod( Message<?> message, @Header(ServiceHeader.A_STATE) AState state, @Header(ServiceHeader.A_ID) String id) { ... } ... } At the moment, I call this service method from within a Spring Integration Java DSL (spring-integration-java-dsl:1.0.1.RELEASE)...

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,...

OrElseGet chaining in Java8

lambda,java-8,optional
I have a list in which 50 values are coming. Now I have 3 matching conditions, however matching conditions have some order. Like for P1 condition I have to match first, if it does not matches in any element then second condition should be evaluated for logic and so on....

Not getting correct timezone in Java 8?

java,java-8,java-time
I have set my system data time to Asia/Kolkata and it is: Date: 2015-06-12 Time: 12:07:43.548 Now i have written following program in Java 8 ZoneId paris = ZoneId.of("Europe/Paris"); LocalDateTime localtDateAndTime = LocalDateTime.now(); ZonedDateTime dateAndTimeInParis = ZonedDateTime.of(localtDateAndTime, paris ); System.out.println("Current date and time in a particular timezone : " +...

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()...

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 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...

C# + linq(concat) rewrite to java

java,c#,linq,java-8
I have a code example in C# (with linq) but am trying to translate this to java code (java 8). But am getting very confused about what happens. Also i am not able to reproduce the same result in java as from the c# code. public IEnumerable<Node> GetNeighborNodes(Node v) {...

Implementing swing in jdk 1.8 using eclipse

java,eclipse,swing,java-8
I was trying to implement the concept of swing using eclipse in jdk 1.8 but when I used the identifier like JButton then an error came : The type JButton is not accessible due to restriction on required library C:\ProgramFiles \Java\jre 1.8.0_31\lib\rt.jar I am a newbie Java programmer.Can someone please...

What does :: operator Java means? [duplicate]

java-8
This question already has an answer here: :: (double colon) operator in Java 8 5 answers I saw some tutorial over YouTube, and the lecturer used :: like: public static void main(String[] args) { List<Integer> l = Arrays.asList(1,2,3,4,5,6,7,8,9,10); Integer s = l.stream().filter(Tests::isGT1) .filter(Tests::isEven) .map(Tests::doubleIt) .findFirst() .orElse(100); System.out.println(s); } private...

First Object in Set> that satisfies a predicate

java,functional-programming,java-8,future,rx-java
Abstract idea I want to get the first value coming out of a set of Futures, that satisfies a given predicate. If a satisfying value is found, all other Futures should be cancelled. If no value is found after all Futures have returned the execution should be terminated (by returning...

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);...

Coverting String to LocalTime with/without nanoOfSeconds

java,java-8,formatter,java-time,localtime
I need to convert a string to LocalTime (java-8 not joda) that may or maynot have nanoOfSeconds in the string. The String format is in the form of 07:06:05 or 07:06:05.123456 The string may or may not have a decimal place in the seconds and when it does there could...

Cannot load font in JRE 8

java,fonts,awt,java-8
I cannot load a font from an S3 Inputstream in JRE 8. I do not have issue if a system is installed with JRE 7, JDK 7, or even JDK 8. val fontInputStream = s3Client.getObject(bucketName, objectKey).getObjectContent val customFont = Font.createFont(Font.TRUETYPE_FONT, fontInputStream).deriveFont(Font.TRUETYPE_FONT, 20F) The error that I got is Exception in...

How to parse non-standard month names with DateTimeFormatter

java,datetime,localization,java-8,java-time
I need to parse (German) dates that come in the following form: 10. Jan. 18:14 8. Feb. 19:02 1. Mär. 19:40 4. Apr. 18:55 2. Mai 21:55 5. Juni 08:25 5. Juli 20:09 1. Aug. 13:42 [...] As you can see, the month names are cut if the month has...

Center JoptionPaneMessageDialog in parent element of the source element that generated the event

java,swing,events,java-8
I need to center the JOptionPaneMessageDialog in the parent element of e.getSource. The problem is that I have two differents classes. One listener class and another class that use that listener this is the line that I need to change JOptionPane.showMessageDialog((Component)e.getSource(), "pulsado"); package excepciones; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Toolkit;...

Trying to use lambda for the first time and the code doesn't compile [closed]

eclipse,lambda,java-8
I trying to use the lambda expressions in Java-8 using eclipse IDE. I took this example from some youtube tutorial which worked well there, but in my code it doesn't and it gave me this error. I tried to add Integer before the value and it still the same. How...

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...

Java8 LocalDate Time Adding Hours Not Wroking

java-8,java-time
I tried like below, but in both the cases it is showing same time? What i am doing wrong. LocalDateTime currentTime = LocalDateTime.now(ZoneId.of("UTC")); Instant instant = currentTime.toInstant(ZoneOffset.UTC); Date currentDate = Date.from(instant); System.out.println("Current Date = " + currentDate); currentTime.plusHours(12); Instant instant2 = currentTime.toInstant(ZoneOffset.UTC); Date expiryDate = Date.from(instant2); System.out.println("After 12 Hours =...

Java8 LocalDateTime to XMLGregorianCalender Remove “+05:30” Portion

java-8,java-time
Did like below, LocalDateTime currentUTCTime = LocalDateTime.now(ZoneId.of("UTC")); String reqPattern = currentUTCTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS")); System.out.println("Required pattern: " + reqPattern); GregorianCalendar calendar = GregorianCalendar.from(currentUTCTime.atZone(ZoneId.systemDefault())); XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); System.out.println("But Showing As :" + xcal); I want the output as 2015-06-18 11:59:15:135, but when i set the...

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...

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; }...

Are interfaces a valid substitute for utility classes in Java 8? [duplicate]

java,class,interface,java-8,utility-method
This question already has an answer here: Java 8: Interface with static methods instead of static util class 4 answers For the past decade or so, I've been using the pattern below for my Java utility classes. The class contains only static methods and fields, is declared final so...

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:...

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; }...

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;...

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...

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 - return List (keyset) opposed to List>

java,java-8,vaadin
I am trying to use java 8 to return me a list of key values(Integers) in which the value (Checkbox) is checked. The map I am trying to process is of the following form. Map<Integer, CheckBox> The aim is to return the key set for all values where the check...

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 - Call interface's default method with double colon syntax

java,inheritance,lambda,java-8
I'm delving into the Java 8 innovations, and I'm trying to call a default method which I implement in a high-level interface, even when a subclass overrides it. I would have no problem going back to implementing a Comparator in my BusinessLogic class, but I was wondering if there's some...

Do repeating annotations need a public container?

java,eclipse,java-8,javac,repeating-annotations
I noticed a discrepancy between Eclipse's compiler and javac while using repeating annotations. The repeating annotation and its container were in the same package, but the former was declared public, while the latter remained package-private. Eclipse had no problem with the arrangement, even though the repeating annotation was referenced in...

Stuck with java8 lambda expression

java,java-8
I have Map<Integer,Doctor> docLib=new HashMap<>(); to save class of Doctor. Class Doctor has methods:getSpecialization() return a String, getPatients() to return a collection of class Person. In the main method, I type: public Map<String,Set<Person>> getPatientsPerSpecialization(){ Map<String,Set<Person>> res=this.docLib.entrySet().stream(). map(d->d.getValue()). collect(groupingBy(d->d.getSpecialization(), d.getPatients()) //error ); return res; } As you can see, I have...

How To Calculate The Number Of Days In A Period

java,java-8
For the following Period calculation: Period.between(LocalDate.of(2015,8,1), LocalDate.of(2015,9,2)) the result is: P1M1D This is equivalent to 31 days + 1 day = 32 days. For this Period: Period.between(LocalDate.of(2015,8,1), LocalDate.of(2015,10,2)) the result is : P2M1D This is equivalent to: 31 days (in August) + 30 days (in September) + 1 (in October)...

Java 8: Filtering Map to List by person's status

java,lambda,java-8
I'm trying to filter a Map<Long, Person> people and return only the IDs of these people having a status of SUBSCRIBED in a List<Long>. Here is the code in the old-fashioned way: public List<Long> getSubscribedPeople() { final List<Long> subscribedPeople = new ArrayList<>(); for (final Map.Entry<Long, Person> entry : subscribedPeople.entrySet()) {...

Why I'm getting different java versions

java,terminal,java-8
I just upgraded my Java from 1.8 update 31 to update 45. Once done, I checked in the Java Console it shows Java 8 update 45. But, when I checked in the terminal it shows java version "1.8.0_31". I checked using Verify Java Version, and it show You have the...

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...

How to check if Collection is not empty using java Stream

java,lambda,stream,java-8
I am new to Java 8. I am not able to understand what is wrong in the following piece of code. The idea is to sent Collection if its not empty . But if the collection is empty than sent HttpStatus.NOT_FOUND Entity response. @RequestMapping(value = "/find/pks", method = RequestMethod.GET, produces...

How to use lambda expression to call the comparator?

java,lambda,java-8
I am doing the leetcode's largest Number problem. Here is the problem: Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. and there is a 5 lines C# code:...

JavaFx: Button border and hover

java,css,javafx,java-8
I am using Java 8. I have toolbar and buttons on it. I want to implement the following: In usual state (without mouse hover) at toolbar, only button label must be seen (no background, nor borders). When the user mouse hovers over the button, then the usual button must be...

RoundingMode.HALF_DOWN issue in Java8

java,java-8,rounding,number-rounding
I am using jdk 1.8.0_45, and our tests discovered a bug in rouding. RoundingMode.HALF_DOWN works the same as RoundingMode.HALF_UP when the last decimal that decide the rounding is 5. I found related issues with RoundingMode.HALF_UP, but they are fixed in update 40. I also put a bug to the oracle,...

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...

Generic method to perform a map-reduce operation. (Java-8)

java,function,generics,java-8,overloading
How to overload a Function with generic parameter in Java 8? public class Test<T> { List<T> list = new ArrayList<>(); public int sum(Function<T, Integer> function) { return list.stream().map(function).reduce(Integer::sum).get(); } public double sum(Function<T, Double> function) { return list.stream().map(function).reduce(Double::sum).get(); } } Error: java: name clash: sum(java.util.function.Function<T,java.lang.Double>) and sum(java.util.function.Function<T,java.lang.Integer>) have the same erasure...

Java 8 Stream with batch processing

java,stream,java-8,batch-processing
I have a large file that contains a list of items. I would like to create a batch of items, make an HTTP request with this batch (all of the items are needed as parameters in the HTTP request). I can do it very easily with a for loop, but...

Gradle Android Project with Java 8 module

java,android,gradle,java-8,android-gradle
As I've seen in this post, Java 8 is not officially supported by Android right now. So I'm interested if it is possible to build Android module with Java 7 and Java module (as a dependency) with Java 8. As an example, I'm trying to create a Gradle project that...

How to convert single element list to java 8 optional

java,collections,java-8,optional
How to nicely convert list containing one or zero elements to Optional? The ugly code: List<Integer> integers = new ArrayList<>(); Optional<Integer> optional = integers.size() == 0 ? Optional.empty() : Optional.of(integers.get(0)); ...