eclipse,java-8,nullable,optional , Java 8 Optional.ifPresent is my code wrong or is it eclipse?


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

Question:

Tag: 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 can use :: operator and/or maps).

In Eclipse I have the Java - Compiler - Errors/Warnings - Null Analysis Errors turned on.

My test code below:

public void test1(@Nullable String s) {
    // the 2nd s2 has a Potential null pointer access error. 
    // I was hoping ifPresent would imply NonNull
    Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}

@Nullable 
public String getSomeString() {
    return null;
}

public void test2() {
    String s = getSomeString();

    // This is fine, unlike the first example, I would have assumed that
    // it would know s was still nullable and behave the same way.
    Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}

It would seem that using Eclipse type null annotations and Optional.ifPresent doesn't go well together.

Am I wasting my time trying to get something like this to work? Should I just revert back to assigning the getter to a temp var then checking if null, and if not call my function?


Answer:

JDT's null analysis cannot know about the semantics of each and every method in JRE and other libraries. Therefore, no conclusions are drawn from seeing a call to ifPresent. This can be remedied by adding external annotations to Optional so that the analysis will see method ofNullable as

<T> Optional<@NonNull T> ofNullable(@Nullable T value)

External annotations are supported starting with Eclipse Mars, release due next Wednesday (June, 24, 2015). See Help: Using external null annotations.

The difference between the two variants in the question is due to how null analysis is integrated with Java 8 type inference: In variant (1) s has type @Nullable String. When this type is used during type inference, it is concluded that the argument to ifPresent is nullable, too. In variant (2) s has type String (although flow analysis can see that is may be null after the initialization from getSomeString). The unannotated type String is not strong enough to aid type inference to the same conclusion as variant (1) (although this could possibly be improved in a future version of JDT).


Related:


one eclipse install not displaying utf8


java,eclipse,svn,utf-8
I have Eclipse installed on an old machine and a new machine. I download from svn repository on old Eclipse, UTF8 character in a java file displays fine. I download onto new Eclipse, UTF8 character displays as "?". I deduce that the file is saved correctly in SVN. I have...

Match a pattern preceded by a specific pattern without using a lookbehind


regex,eclipse,lookahead
Is there a way to match a B only if preceded by an A? The A can be at any position behind the B, with any amount of characters between. Examples: A_B (Matches `B`) C_B (No match) I've tried: (?=A)[^B]*B But it matches all the characters preceeding B as well....

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

Close module in android studio


android,eclipse,android-studio
in eclipse there is simple option to close or open project. How can I do it in android studio to close and open module without import it and delete each time?

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

Spring Roo Shell in Eclipse: Could not create sts.roo.ui.rooShellView


eclipse,spring-roo,spring-tool-suite
IDE: springsource-tool-suite-3.6.4.RELEASE-e4.4.2 / eclipse-4.4.2 with sts-3.6.4.201503051146-RELEASE IDE Plugin: Spring IDE Roo Support v3.6.4.201503051146-RELEASE (via Eclipse Marketplace) Maven project configuration for Eclipse AJDT v0.14.0.201302011330 (via http://dist.springsource.org/release/AJDT/configurator/) Spring Roo: spring-roo-1.3.1.RELEASE / spring-roo-2.0.0.M1 Reproduce Step: import project created by Spring-Roo into eclipse right click project choose "Spring Tools" click "Open Roo Shell"...

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

What are my next steps on finding the cause of this exception?


java,android,eclipse,debugging
I'm fairly new to Eclipse, Java, and Android programming. I've taken over development of an Android application. Someone has made a change several months ago that is causing the application to crash (exception) in code that is not part of the application code. I don't have any idea where or...

How to save a json file locally with dojo toolkit


javascript,android,json,eclipse,dojo
I'm trying to create a JSON file with dojo toolkit that need to be saved into local memory of the phone. The app need to be valid for android and IOS. I'm using ECLIPSE with ADT as a IDE. My principal issue is that normally the file created with dojo...

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

html form action not working when using eclipse


java,eclipse,jsp,servlets
I am new to JSP and Java Servlet. I was going through this tutorial by Java Brains. In this tutorial get and post method is handled. I wrote my html code under web-content. </head> <body> <form action="http://localhost:8080/SimpleServletProject/hello" method="post"> <input name="userName" /> <input type="submit" /> </form> </body> Following is the hello.java...

How to change Eclipse IDE GUI icons?


eclipse,user-interface,icons
Elipse icons are ugly. Fact! I would like to replace the icons with more flat, monochromatic and minimalist icons, but I can't find documentation on how to change icons from Eclipse's user interface. How could I do this? It's needed to recompile eclipse?...

apply formatter only on edited code - eclipse [duplicate]


java,eclipse,save,formatter
This question already has an answer here: How to turn off the Eclipse code formatter for certain sections of Java code? 10 answers I have implemented a formatter in eclipse for my code, when I try to save the changes it applies formatting on complete file. Is it possible...

Remote debugging tomcat with OpenShift


eclipse,tomcat,openshift,remote-debugging
I am using openshift for my tomcat webapp. I am able to run the app but unable to debug it. As openshift starts tomcat in debug mode, I was expecting I'll be able to debug. Host: $OPENSHIFT_JBOSSEWS_IP Value of this is 127.5.20.129 for me which I got from command: rhc...

No hello World output for Neo4j


java,eclipse,neo4j
I am just starting out with Neo4j and this is my first stackoverflow question! I tried to run the Hello-World example in Eclipse with the user library of Neo4j. ( https://github.com/neo4j/neo4j/blob/2.2.2/community/embedded-examples/src/main/java/org/neo4j/examples/EmbeddedNeo4j.java) I only changed the DB_PATH='data/graph.db' ( because in my neo4j-server.properties :org.neo4j.server.database.location=data/graph.db) The output I got in the console is:...

Java eclipse I want to open the form like tab [on hold]


java,eclipse
Java eclipse: I want to open the form as shown below http://i.stack.imgur.com/U0wT5.png...

Open a properties file from a class in a Dynamic Web Project


java,eclipse,jsp,properties-file
I'm using Eclipse for EE Developer. I need to access to a properties file (db.properties) from a class's method (DBQuery.java). The class is located inside a package inside the src folder. For the properties file i tried almost everything that i could find over the net to make it work,...

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

Eclipse not compiling because of ClassNotFoundException


java,eclipse,amazon-web-services,compilation,aspectj
After following an AWS tutorial for Eclipse, my code no longer compiles and runs. I decided to undo what the tutorial told me, so I may have changed some settings that I forgot to unchanged but I really cannot find the root of my problem. Eclipse seems to be back...

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

JSF facets not available in Eclipse


java,eclipse,jsf,facets
So I am watching a tutorial about how to configure JSF in eclipse. I understand that you click file -> new -> Dynamic Web Project. And then it gives you a few options. The Target Runtime will be (for me) Apache Tomcat version 8, and dynamic web module version will...

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

Disable Wrapping Cursor in Eclipse


eclipse,vim,vi
I'm mostly using Vi (edit: Vim) for text editing and the viPlugin for Eclipse Juno. Eclipse seems to have a very annoying behaviour of "wrapping" the cursor to the next/previous line, if yout reach the end/start of a line through cursor keys. (Reproduce by placing the cursor on the first...

Eclipse CDT - No Console Output on OSX


c++,eclipse,osx,terminal,64bit
New to the C++ world and wanted to fiddle around using Eclipse's IDE for C/C++ called CDT. I am on OSX 10.10.2 using eclipse-cpp-luna-SR2-macosx-cocoa-x86_64. Sadly this simple example is not printing anything in the eclipse terminal. #include <iostream> using namespace std; int main() { cout << "Hello World" << endl;...

Compilation Error on maven


java,eclipse,maven,maven-plugin
Working on maven project. I m trying to build using maven but I m getting the following error! I m working on eclipse using JDK 8. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) I also tried the above solution, but still I m getting error! [INFO] Scanning for projects... [INFO] [INFO]...

IntelliJ - use imported modules as dependencies like maven projects in Eclipse


eclipse,scala,maven,intellij-idea,sbt
I've been asking myself this question for a couple of years but never really found the solution. I used to work with eclipse (on maven java projects). I could import a project -let's call it 'proj-A'- and if one of proj-A's dependencies was found in the workspace with the same...

How to find references to a class that's referenced indirectly via exported jar in Eclipse?


java,eclipse
I have two Eclipse projects, Project_A and Project_B. Project_B is compiled and exported as a .jar file that's used by Project_A. Is there a way to select a class in Project_B and find all references to it in both Project_A and Project_B? Normally I'd use "Find all References" (Ctrl +...

Eclipse Layout: static instead of relative values?


android,eclipse,layout
I have a layout with two Buttons. One button is in the Center of the left half, and the other button is in the Center of the right side. But I use relative values (left="60dp" etc.). How can I have the same result with static values? Because I don't want...

guidance needed on using apache commons math


java,eclipse,apache
I am trying to utilize the Apache Commons Math (3.5) library in Eclipse IDE. I have downloaded the JAR file and have added the library to my project correctly. However my problem lies when I actually try using classes from the Apache Commons library. I try to create a new...

Can I install 2 or more Android SDK when using Eclipse


java,android,eclipse,sdk,versions
I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

Tomcat 7 PermGen Space or Failed to Create JVM


java,eclipse,tomcat,tomcat7,permgen
I'm currently searching for any help about this. I'm trying to start a Tomcat 7 server, but I only get PermGen Space exception. I tried to change the XXMaxPermSize value, but when I change it, I get a Pop Up at launch of my Eclipse : "Failed to Create the...

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

Why does Eclipse reference a 1.4 JRE?


java,eclipse
When attempting to create a new Java Project, eclipse is telling me that the workspace is using a 1.4 JRE (see screenshot). Any ideas why it might be saying this? I don't even have a 1.4 JRE installed on my machine. I'm using GGTS 3.5.1 on Juno 3.8.2. My GGTS.ini...

Java: unhandled exception


java,eclipse,exception,exception-handling,try-catch
I would like to handle an exception but the Eclipse editor is giving me tips which I'm not understanding. This is the method's code: public Collection<String> listOfFriends(String codePerson) throws NoSuchCodeException { Collection<String> s = new LinkedList<>(); try { people.get(codePerson).getFriendsCodes().forEach( code -> s.add(getPerson(code))); } catch (Exception e) { e.printStackTrace(); } return...

Showing previous searches in PyCharm


eclipse,full-text-search,pycharm
Eclipse allows viewing one's previous searches in one's search history even going so far as to show the exact state in which one left a previous search. For example, if one removed (i.e. excluded) a search result from a previous search, that previous search is shown without that search result...

Mysterious claim of a missing { in eclipse


java,eclipse
I have a case of a mysterious missing curly brace that I don't see any use for. Eclipse says, "Syntax error on token ";", { expected after this token". Either I am missing something very silly or there is something new I have to learn about Java. This is the...

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

Scala running issue on eclipse


eclipse,scala
I configured everthing within eclipse for scala. I create a snippet to show you the issue, i can't see in run options run as scala application, i also tried to find my main class under build configuration option but i can't find it. How i can solve it?...

Modify ivy classpath entry


java,eclipse,eclipse-plugin,ivy,ivyde
In the picture below, I want Ivy settings path to NOT include ${ivyproject_loc} Property Files to NOT include ${project_loc} Here is what I have right now. I was thinking it might be easier to remove the ivy library and add it the way I want it. I know how to...

exec-maven-plugin error, even on working example


java,eclipse,maven
EDIT5 Updated / I'm using Maven 3.3.3. I just create new project and added compile and exec plugin, as examples on web. I tried to execute, but I got error [ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project QNAProject: An exception occured while executing the Java class. com.jadex.qna.QNAProject.App ->...

Eclipse CDT shows … not resolved errors for ARM neon intrinsics, but produces the binary


c++,eclipse,arm,neon
I develop ARM-Neon based embedded software for Cortex A8 and A9 processors. I use Eclipse CDT Luna for development environment. I opened a project and added #include "arm_neon.h" at the beginning of my main code, and the following flags to both C++ compiler and linker miscellaneous flags part in project...

Meaning of connectionTimeout in tomcat


java,eclipse,tomcat
What does that parameter mean for tomcat. It was declared in server.xml as follows: <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> So, I tried to change it <Connector connectionTimeout="2" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> and didn't notice any effect. I expected that each page the load takes for more than 2 milliseconds would produce...

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

How to force team members to comment using eclipse plugin or something else


eclipse,jenkins,eclipse-plugin,coding-style,build-automation
Currently, I am working in a new project and it was difficult for me to understand since there is no comment. I wonder if it is possible to force team members(including me) to add more comments. I would like to automate this ject in jenkins later if possible.

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

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]


java,android,eclipse,adt
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat http://i.stack.imgur.com/VZhuL.png package...

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

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

Importing Spring MVC Project Manually to Eclipse


java,eclipse,spring,spring-mvc
I have a little problem. I had googled for this problem and I haven't found any solution related. My problem is, my office internet using proxy that banned me to download zip file. I need Spring MVC Project template in Spring Tool Suite (STS). So I downloaded the zip file...