Java stream predicate not

Negating a Predicate in Java

Learn to create a Predicate with the negating effect that will match all the elements not matching the original predicate. The negated predicate acts as a pass function and selects all the elements from the stream that were filtered out by the original predicate.

1. Predicate negate() Method

The Predicate.negate() method returns the logical negation of an existing predicate.

Predicate isEven = i -> i % 2 == 0; Predicate isOdd = isEven.negate();

Use these predicates as follows with the Stream filter() method.

List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Predicate isEven = i -> i % 2 == 0; Predicate isOdd = Predicate.not( isEven ); List evenNumbers = list.stream() .filter(isEven) .collect(Collectors.toList()); List oddNumbers = list.stream() .filter(isOdd) .collect(Collectors.toList());

2. Predicate not() Method – Java 11

In Java 11, Predicate class has a new method not() . It returns a Predicate that is the negation of the supplied predicate.

Internally, this is accomplished by returning the result of the calling predicate.negate() .

Predicate isEven = i -> i % 2 == 0; Predicate isOdd = Predicate.not( isEven );

Drop me your questions related to Java stream predicate negate examples.

Источник

Negate a Predicate Method Reference with Java 11

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

Читайте также:  Content formatting in html

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this short tutorial, we’ll see how to negate a Predicate method reference using Java 11.

We’ll start with the limitations encountered in order to achieve this before Java 11. Then we’ll see how the Predicate.not() method helps, as well.

2. Before Java 11

First, let’s see how we managed to negate a Predicate before Java 11.

To start with, let’s create a Person class with an age field and an isAdult() method:

public class Person < private static final int ADULT_AGE = 18; private int age; public Person(int age) < this.age = age; >public boolean isAdult() < return age >= ADULT_AGE; > >

Now, let’s imagine we have a list of people:

List people = Arrays.asList( new Person(1), new Person(18), new Person(2) );

And we want to retrieve all the adult ones. To achieve that in Java 8, we can:

people.stream() .filter(Person::isAdult) .collect(Collectors.toList());

However, what if we want to retrieve the non-adult people instead? Then we have to negate the predicate:

people.stream() .filter(person -> !person.isAdult()) .collect(Collectors.toList());

Unfortunately, we are forced to let go of the method reference, even though we find it easier to read. A possible workaround is to create an isNotAdult() method on the Person class and then use a reference to this method:

people.stream() .filter(Person::isNotAdult) .collect(Collectors.toList());

But maybe we don’t want to add this method to our API, or maybe we just can’t because the class isn’t ours. That’s when Java 11 arrives with the Predicate.not() method, as we’ll see in the following section.

Читайте также:  Checkbox php mysql примеры

3. The Predicate.not() Method

The Predicate.not() static method has been added to Java 11 in order to negate an existing Predicate.

Let’s take our previous example and see what that means. Instead of using a lambda or creating a new method on the Person class, we can just use this new method:

people.stream() .filter(Predicate.not(Person::isAdult)) .collect(Collectors.toList());

That way, we don’t have to modify our API and still can rely on the readability of method references.

We can make this even clearer with a static import:

people.stream() .filter(not(Person::isAdult)) .collect(Collectors.toList());

4. Conclusion

In this short article, we’ve seen how to leverage the Predicate.not() method in order to maintain usage of method references for predicates, even if they are negated.

As usual, the full code of the article can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Digital Transformation and Java Video Training

Java | Integration | MuleSoft | Digital Transformation | API-led connectivity | RESTful API

Java 8 Streams: .filter and Predicate Negation

Posted on November 17, 2015 by Alex in Java 8 // 4 Comments

Recently there was an interesting discussion on the use of predicate negation in the .filter method on a stream by members of the LJC mailing list, so I thought it would be worth summarizing it in a blog post. The discussion was about ways to use .filter and to negate the predicate.

Code for this post is available in my GitHub account.

Question: How can you use .filter to negate the predicate

This is perhaps how you might think about doing,

Stream.of(1, 2, 3, 4, 5, 6, 7) .filter(((Predicate) c -> c % 2 == 0).negate())

but here are some alternative ways.

Answer 1: Write a predicate utility method

You can simplify this by writing a utility method that performs the negation.

public static Predicate not(Predicate predicate)

Which results in much neater code.

Stream.of(1, 2, 3, 4, 5, 6, 7) .filter(not(c -> c % 2 == 0))

Answer 2: Use an identity function to convert the method reference to a Predicate

We use a utility method to convert a method reference to a predicate.

public static Predicate predicate(Predicate predicate)

although the code is not as neat.

Stream.of("Cat", "", "Dog") .filter(predicate(String::isEmpty).negate())

Answer 3: Use the not (!) operator

Use the familiar, not operator.

Stream.of(1, 2, 3, 4, 5, 6, 7) .filter((c -> c % 2 != 0)) Stream.of("Cat", "", "Dog") .filter(str -> !str.isEmpty())

The code is much simpler and immediately familiar.

Читайте также:  192 168 main html

Conclusion

It is argued that method references are often harder to read and are trickier when refactoring than simple lambdas and that mixing lambdas and method references in a Stream chain is confusing to the reader. Reference: Java SE 8 Best Practices

When you use a method reference and want the IDE to create the method, IntelliJ creates this as a static method with the object as the first argument. Using the not operator avoids this.

Here are some useful references:

Источник

Predicate not() Example – Java 11

This method returns a predicate that is the logical negation of the given predicate.

2. How to use it?

Let’s take an example where we have the lambda expression to retrieve ‘Even’ numbers and to get ‘Odd’ numbers, we are going to use ‘not()’ method.

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks. View all posts

Submit a Comment Cancel reply

Subscribe to our Newsletter

About Techndeck

Techndeck.com is a blog revolves around software development & testing technologies. All published posts are simple to understand and provided with relevant & easy to implement examples.

Techndeck.com’s author is Deepak Verma aka DV who is an Automation Architect by profession, lives in Ontario (Canada) with his beautiful wife (Isha) and adorable dog (Fifi). He is crazy about technologies, fitness and traveling etc. He runs a Travel Youtube Channel as well. He created & maintains Techndeck.com

This website uses cookies to improve your experience. We’ll assume you’re ok with this, but you can opt-out if you wish. Cookie settingsACCEPT

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

Оцените статью