java-8,guava,optional , How to wrap a method that returns an optional <T> with fromNullable?


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

Question:

Tag: 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?

import com.google.common.base.Optional;

private Optional<Boolean> get_I_dontHaveControlOverThisMethod () {
    return null;  // Ooops!
}

// Compile error? ----------------------->  vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Optional<Boolean> x = Optional.fromNullable(get_I_dontHaveControlOverThisMethod());   
// (#1) Optional<Boolean> x = Optional.fromNullable(null);  // <- this work fine
// (#2) Optional<Boolean> x = get_I_dontHaveControlOverThisMethod();
if (x.isPresent()) {   // <- this blows up!  NPE when (#2) runs
    // non-null good value;
}

enter image description here


Answer:

Use

Optional<Boolean> x = get_I_dontHaveControlOverThisMethod();
if(x == null) x = Optional.absent();

If you are calling such methods quite often, you can wrap it into function:

static <T> Optional<T> safeOptional(Optional<T> optional) {
    return optional == null ? Optional.absent() : optional;
}

And use:

Optional<Boolean> x = safeOptional(get_I_dontHaveControlOverThisMethod());

Related:


Iterating over a map and putting its values in java


java,guava
I have created the data structure that is google based guava table and it is shown below final Table<String, String, List<String>> values = HashBasedTable.create(); values.put("ton bon", "currency", Lists.newArrayList("ccdd", "rode1", "cwey", "Certy")); values.put("ton bon", "racy", Lists.newArrayList("wqadd", "werde", "ihtr", "ytre")); Below is the way in which i am iterating over this collection...

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

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

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

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

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

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

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

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

Joining a collection based on members of the type


java,functional-programming,guava,method-chaining
I have a class A and its members b and c. Now I construct the List<A> with this: add(new A().setb("abcd").setc("123456")); add(new A().setb("efgh").setc("789101")); add(new A().setb("ijkl").setc("112345")); I want to transform this List to string which looks like this abcd,123456 efgh,789101 ijkl,112345 Now the very obvious way would be to have a StringBuilder...

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

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

How is Guava Splitter.onPattern(..).split() different from String.split(..)?


java,regex,split,guava
I recently harnessed the power of a look-ahead regular expression to split a String: "abc8".split("(?=\\d)|\\W") If printed to the console this expression returns: [abc, 8] Very pleased with this result, I wanted to transfer this to Guava for further development, which looked like this: Splitter.onPattern("(?=\\d)|\\W").split("abc8") To my surprise the output...

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

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

How to index a multimap based on several criteria?


java,guava
I have a List of "SomeClass" which may consist of a lot of functionally equal objects, and I need to group these. The entries with identical getName(), getInputDate(), getOutputDate() and getValue() should be grouped together. I came across Multimap which seems to be what i need, but I can't figure...

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

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

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

How long does an event live in the eventbus?


java,guava
I would like to @Subscribe a method in a Runnable that is created by a ScheduledFuture, so that I can signal it from another thread whether to run. Because a ScheduledFuture creates the object at some future time, there is no scope for the @Subscribe listener to pick up my...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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