java-8,optional,java-stream , Optional.ifAbsentThrow()?


Optional.ifAbsentThrow()?

Question:

Tag: java-8,optional,java-stream

Suppose I need to find a value of a certain order, then get its id, and then its localized-id. And if I can't do it, I want to throw and exception:

return values.stream()
             .filter(value -> value.getOrder("order") == order)
             .findAny()
             .map(Attribute::getId)
             .map(Id::getLocalizedId)
             .orElseThrow(() -> new RuntimeException("Could not get the localized id of the value of order " + order));

The problem is that the exception is not very detailed: it tells me I can't get the localized-id, but not why.

I miss some Optional.ifAbsentThrow method that would allow me to do this:

return values.stream()
             .filter(value -> value.getOrder("order") == order)
             .findAny()
             .ifAbsentThrow(() -> new RuntimeException("Could not find value of order " + order));
             .map(Attribute::getId)
             .ifAbsentThrow(() -> new RuntimeException("Value of order " + order + " has no id"));
             .map(Id::getLocalizedId)
             .orElseThrow(() -> new RuntimeException("Could get the id but not the localized id of the value of order " + order));

To solve this problem, I have created the following ifAbsentThrow method:

public static <T, X extends RuntimeException> Predicate<T> ifAbsentThrow(Supplier<? extends X> exceptionSupplier) throws RuntimeException {
    return valor -> { 
                    if (valor == null) throw exceptionSupplier.get();
                    return true; 
                    };
    }

And I use it like this:

return values.stream()
             .filter(value -> value.getOrder("order") == order)
             .findAny()
             .filter(ifAbsentThrow(() -> new RuntimeException("Could not find value of order " + order));
             .map(Attribute::getId)
             .filter(ifAbsentThrow(() -> new RuntimeException("Value of order " + order + " has no id"));
             .map(Id::getLocalizedId)
             .orElseThrow(() -> new RuntimeException("Could get the id but not the localized id of the value of order " + order));

My Questions:

Edit: It now seems to me that Optional.ifAbsentThrow does not exist because it would be a way of dealing with null values, and Optional is all about not using null values in the first place. Optional clearly doesn't play well with null values, it gets verbose if you mix them. However, in the real world I find it difficult to deal with this all-or-nothing proposition: Some code gets translated to Optionals, while other remains using nullable values. To help me mix them, and refactor nullables to Optionals only when necessary, I believe I will be using the GetNonNull class below, built upon knowledge I gained from @Alex and @Holgers answers in this page.


Answer:

Based on the knowledge I gained from @Alex and @Holgers answers in this page, I have developed the following GetNonNull class, focused on readability:

Optional<Value> value = values.stream()
                              .filter(value -> value.getOrder("order") == order)
                              .findAny();
return GetNonNull
          .mapOrThrow(value, () -> new RuntimeException("Got no value."))
          .mapOrThrow(Value::getAttribute, () -> new RuntimeException("Got value, but no attribute."))
          .mapOrThrow(Attribute::getId, () -> new RuntimeException("Got value and attribute, but no id."))
          .mapOrThrow(Id::getLocalizedId, () -> new RuntimeException("Got value, attribute and id, but no localized id."))
          .get();

I find this functional code very easy to read, and it concentrates all exception handling code together (no need to add orElseThrow to the end of the stream). The GetNonNull name implies that the end result will never be null.

Compare it with the alternative imperative code:

if (valor == null) throw new RuntimeException("Got no value.");
Attribute attribute = valor.getAttribute();
if (attribute == null) throw new RuntimeException("Got value, but no attribute.");
Id id = attribute.getId();
if (id == null) throw new RuntimeException("Got value and attribute, but no id.");
String localizedId = id.getLocalizedId();
if (localizedId == null) throw new RuntimeException("Got value, attribute and id, but no localized id.");
return localizedId;

Instead of throwing, you may also return an Optional:

return GetNonNull
          .mapOrThrow(value, () -> new RuntimeException("Got no value."))
          .mapOrThrow(Value::getAttribute, () -> new RuntimeException("Got value, but no attribute."))
          .mapOrThrow(Attribute::getId, () -> new RuntimeException("Got value and attribute, but no id."))
          .getOptional(Id::getLocalizedId); // Changed here.

Or you may return a non-null default value:

return GetNonNull
          .mapOrThrow(value, () -> new RuntimeException("Got no value."))
          .mapOrThrow(Value::getAttribute, () -> new RuntimeException("Got value, but no attribute."))
          .mapOrThrow(Attribute::getId, () -> new RuntimeException("Got value and attribute, but no id."))
          .getOrDefault(Id::getLocalizedId, "DEFAULT"); // Changed here.

It is also Optional/null agnostic, i.e., nothing changes if the initial value is a regular nullable value, instead of an Optional:

Value value = ...; // Not an Optional.

return GetNonNull
          .mapOrThrow(value, () -> new RuntimeException("Got no value."))
          .mapOrThrow(Value::getAttribute, () -> new RuntimeException("Got value, but no attribute."))
          .mapOrThrow(Attribute::getId, () -> new RuntimeException("Got value and attribute, but no id."))
          .mapOrThrow(Id::getLocalizedId, () -> new RuntimeException("Got value, attribute and id, but no localized id."))
          .get();

You can also use it as a simple functional get-default-value idiom. This:

Value value = ...;
if (value != null) return value;
else if (default != null) return default;
else throw new NullPointerExeption();

May be written as:

// Shorter and more readable then Optional.ofNullable(value).orElse(default).
// Also not the same, because here a NullPointerException is raised if default is null.
return GetNonNull.getOrDefault(value, default);

And this:

Optional<Value> value = ...;
if (value.isPresent()) return value;
else if (default != null) return default;
else throw new NullPointerExeption();

May also be written exactly the same:

return GetNonNull.getOrDefault(value, default);

Since the GetNonNull class is compatible with both nullables and Optionals, if some legacy imperative code that use nullable values gets later refactored to use Optionals, the GetNonNull usage needs not to be changed.

Here it is:

public final class GetNonNull<T, E extends Throwable> {
    private final T value;
    private final E failure;

    private GetNonNull(T value, E failure) {
        this.value = value;
        this.failure = failure;
        if ((value == null) && (failure == null)) throw new NullPointerException();
        }

    public T get() throws E {
        if (failure != null) throw failure;
        return value;
        }

    public <R> Optional<R> getOptional(Function<T, R> f) throws E {
        if (failure != null) throw failure;
        if (value != null) {
            R result = f.apply(value);
            return Optional.ofNullable(result);
            }
        return Optional.empty();
        }

    public static <R> R getOrDefault(R o1, Supplier<R> supplier) {
        if (o1 != null) return o1;
        R result = supplier.get();
        if (result != null) return result;
        else throw new NullPointerException();
        }

    public static <R> R getOrDefault(R o1, R o2) {
        if (o1 != null) return o1;
        else if (o2 != null) return o2;
        else throw new NullPointerException();
        }

    public static <R> R getOrDefault(Optional<R> o1, R o2) {
        if (o1.isPresent()) return o1.get();
        else if (o2 != null) return o2;
        else throw new NullPointerException();
        }

    public <R> R getOrDefault(Function<T, R> f, R o) throws E {
        if (failure != null) throw failure;
        if (value != null) {
            R result = f.apply(value);
            if (result != null) return result;
            else return o;
            }
        return o;
        }

    public <R> GetNonNull<R, E> mapOrThrow(Function<T, R> f, Supplier<E> s) {
        if (value != null) {
            R result = f.apply(value);
            return new GetNonNull<>(result, (result != null) ? null : s.get());
            }
        return (GetNonNull)this;
        }

    public static <T, E extends Throwable> GetNonNull<T, E> getOrThrow(Optional<T> o, Supplier<E> s) {
        return o.map(t -> new GetNonNull<>(t, (E)null)).orElseGet(() -> new GetNonNull<>(null, s.get()));
        }

    public static <T, E extends Throwable> GetNonNull<T, E> mapOrThrow(T o, Supplier<E> s) {
        return getOrThrow(Optional.ofNullable(o), s);
        }
    }

Related:


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

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

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

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

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

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

array created with optional


ios,swift,optional
I am declaring a array: var array:[String] = [] assigning values: array.append(uniqueId as String) and then pass it to a function: static var levels_array : [String] = [] class func setLevelsArray(arr:[String]) { GamePrefrences.levels_array = arr println(GamePrefrences.levels_array) } My problem is that when i print the array i get: [Optional(88868658), Optional(112051080),...

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

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

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

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

Fatal error when unwrapping CLLocation Location Coordinate


ios,iphone,swift,ios8,optional
I currently have a test application to teach myself Core Location. It is an app with a button which will either show your location when you press a button, or an alert when location services are off. I get a fatal error (unexpectedly found nil when unwrapping option value) When...

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

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

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

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

Whose view is not in the window hierarchy? Swift


ios,swift,optional
I want a table view controller to be displayed. Therefore I present the view controller in the completionwithitemshandler property below. let activityViewController = UIActivityViewController(activityItems:[memeedimage] , applicationActivities: nil) presentViewController(activityViewController, animated: true, completion: nil) activityViewController.completionWithItemsHandler = { (activity, success, returneditems, error) in println("Activity: \(activity) Success: \(success) Items: \(returneditems) Error: \(error)") self.save()...

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

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

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

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

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

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

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

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

Mockito error with method that returns Optional


java,mockito,optional
I have an interface with the following method public interface IRemoteStore { <T> Optional<T> get(String cacheName, String key, String ... rest); } The instance of the class implementing the interface is called remoteStore. When I mock this with mockito and use the method when: Mockito.when(remoteStore.get("a", "b").thenReturn("lol"); I get the error:...

defining functions with optional arguments


python,function,optional,def
Hi I'm trying to understand how to implement optional arguments in a python function. For example, in the basic function below def Ham(p,*q): if q: print p+q else: print p Ham(2) Ham(2,3) I expect Ham(2) to return '2' which it does, however Ham(2,3) gives an error. EDIT: Many thanks. Many...

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

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

What's the meaning of as!,init? in swift?


swift,optional
Sometime when I use "as" ,xcode prompts failed and suggests change to "as!".Also I see some construstors is "init?".I know some variables could be difined as optional.What the meaning of a constructor to be optionsal? I looked up the questions in "the swift programming language",but failed to get the answer....

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

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

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

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

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

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

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

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

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

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