java-8,predicate , Why should functions used for creating a Predicate be defined as static?


Why should functions used for creating a Predicate be defined as static?

Question:

Tag: java-8,predicate

While reading up on the new features introduced in Java 8, I came across the concept of Predicates. I noticed that most of the examples provided on the internet and in books use static functions to create predicates.

Consider the following Apple class for example :

public class Apple {

    private String color;
    private int weight;

    private static final int SMALL_APPLE_MAX_WEIGHT = 150;

    public Apple(String color, int weight) {
        this.color = color;
        this.weight = weight;
    }

    public static boolean isGreenApple(Apple apple) {
        return null!=apple && null!=apple.getColor() && "green".equals(apple.getColor());
    }

    public boolean isBigApple() {
        return this.getWeight() > SMALL_APPLE_MAX_WEIGHT;
    }
}

I can now create a new predicate as follows :

Predicate<Apple> isGreenApple = Apple::isGreenApple;
Predicate<Apple> isBigApple = Apple::isBigApple;

As shown above, I can create a predicate using both a static as well as an instance method. Which approach is the preferred approach then and why?


Answer:

For a method reference, there is no difference between an instance method A.foo() and a static method foo(A), in fact, the compiler will reject a method reference as ambiguous if both exist.

So the decision whether to use an instance method or a static method does not depend on the question whether you want to create a function via method reference for it.

Rather, you have to apply the same considerations us usual. Should the method be overridable, it has to be an instance method, otherwise, if it represents a fixed algorithm, you may consider a static method, but of course, a final method would do as well.

static methods are obviously unavoidable when you are not the maintainer of the class whose instance you want to process, in other words, when the containing class has to be different than the class of the instance. But even if the class is the same but you feel that it could be placed in another (utility) class as well, declaring it as static might be the better choice.

This holds especially when there are more than one parameter and the first one isn’t special to the operation, e.g. max(Foo,Foo) should be a static method rather than an instance method max(Foo) on Foo.

But in the end there are different programming styles out there and the answer is that method references do not mandate a particular programming style.


Regarding why there are so many examples using static methods; well I don’t know enough examples to decide whether your observation is right or just a subjective view. But maybe some tutorial writers are themselves not aware about the possibility to refer to an instance method as a function taking the method receiver as first argument.

I think, there are examples, like

Predicate<String> empty=String::isEmpty;
Predicate<CharSequence> isHello="hello"::contentEquals;

which are worth to be shown in tutorials to emphasize that you are not required to create methods specially intended to be used as method references, but that in fact there are a lot of already existing methods, static and non-static, to be directly usable with method references.


Related:


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Uniqueness and other restrictions for Arbitrary in QuickCheck


haskell,unique,predicate,quickcheck
I'm trying to write a modified Arbitrary instance for my data type, where (in my case) a subcomponent has a type [String]. I would ideally like to bring uniqueness in the instance itself, that way I don't need ==> headers / prerequisites for every test I write. Here's my data...

Linq predicate query results is not working for further Linq Join


c#,linq,dynamics-crm-2011,predicate,linqkit
I am using results from Predicate query to write join in Linq query. Bit it is throwing following error. However when I run similar query in SQL, it return expected results. var predicate = PredicateBuilder.False<Product>(); foreach (var productId in productIds) { var tempGuid = productId; predicate = predicate.Or(p => p.ProductId==...

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

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

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

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

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

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

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

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

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

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

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

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

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