Houston  Sipes

Houston Sipes


How to use map, filter, and collect methods of Java Stream API

Hello, guys! Many of my readers emailed me, asking to write a post about the** map and filter function of Java 8** because they found it difficult to use and understand. Even though I have previously blogged about both the map() and filter(), I am writing this post again to expand on the concept in a layman’s language to provide a better understanding for my readers and fellow Java developers.

The map() function is a method in the Stream class that represents a functional programming concept. In simple words, the map() is used to transform one object into another by applying a function.

That’s the reason the Stream.map(Function mapper) takes a function as an argument. For example, by using the map() function, you can convert a list of String into a List of Integer by applying the Integer.valueOf() method to each String on the input list.

All you need is a mapping function to convert one object to the other. Then, the map() function will do the transformation for you. It is also an intermediate Stream operation which means you can call other Stream methods, like a filter, or collect on this to create a chain of transformations.

Now, coming to the filter method, as its name suggests, it filters elements based upon a condition you gave it. For example, if your list contains numbers and you only want numbers, then you can use the filter method to only select a number that is fully divisible by two.

The filter method essentially selects elements based upon a condition you provide. That’s the reason that the filter (Predicate condition) accepts a Predicate object, which provides a function that is applied to a condition. If the condition evaluates true, then the object is selected. Otherwise, it will be ignored.

Similar to the map, the filter is also an intermediate operation which means you can call other Stream methods after calling the filter.

The filter() the method is also **lazy **which means that it will not be evaluated until you call a reduction method, like collect, and it will stop as soon as it reaches the target.

If you are not familiar with Stream behavior, I suggest you check outLearn Java Functional Programming with Lambdas & Streams by Rang Rao Karnam on Udemy, which explains Stream fundamentals in good detail.

1. How to Use the Map and Filter method in Java 8

You need a good example to understand any new concept. That’s why you are reading this article. Since String and Integer are the most common data type in Java, I have chosen an example which is both simple and interesting.

I have a list of String: numbers like {“1”, “2”, “3”, “4”, “5”, “6”}. I want to process this list and need another List of Integer with just even numbers.

In order to find the even numbers, I first need to convert a List of String to a List of Integer. For that, I can use the map() method of java.util.Stream class. But, before that, we need a Stream as a map() as defined in the java.util.stream class.

This is not difficult at all since you can get the stream from any collection, e.g. List or Set, by calling the stream() method, which is defined in the java.util.Collection interface.

The map(Function mapper) method takes a Function, technically speaking, an object of java.util.function.Function interface. This function is then applied to each element of Stream to convert it into the type you want.

Since we need to convert a String to an Integer, we can pass either the Integer.parseInt() or Integer.valueOf() method to the map() function.

I have chosen the valueOf() method because of the reasons I mentioned in the parseInt vs valueOf article, i.e. performance and caching. By the way, it’s not just me. Even Joshua Bloch has advised preferring static factory methods like valueOf() over constructor in Effective Java.

The map() will then return a Stream of Integer which contains both even and odd numbers. To select just even numbers, we can use the filter() method.

It takes a predicate object which is technically a function to convert an object to boolean. We pass an object and it will return true or false. The filter, then, uses that information to include the object in the result stream.

So, to include only even numbers, we call filter( number -> number%2==0) which means each number will be divided by two, and if there is no remainder, then it will be selected. This is the same logic we have used while solving coding problems to check if a given number is even or odd in Java.

We are almost done. But, so far, we only have the Stream of even integers — not the List of even Integers and that’s why we need to use them.

Since we need a List, I called **collect(Collectors.toList())**, which will accumulate all even numbers into a List and return.

Now, you may be thinking: how does it know to return List of Integer? Well, we need to get that information by Type inference, because we have already specified that information by storing the result into a List<Integer>.

If you want to know more about type inference in a lambda expression,The Complete Java MasterClassis a good place to start.

#coding #programming #learning-to-code #java #software-development #visual studio code

What is GEEK

Buddha Community

How to use map, filter, and collect methods of Java Stream API
Samanta  Moore

Samanta Moore


How to Validate an Email Address in Java

Email is one of the most universal tools for sharing and receiving information across the globe, with users able to connect with others online with almost no compatibility or access issues. Using this tool, information can be instantly and securely sent to partners on the other side of the world, and personal information can be verified without divulging sensitive data about a user.

Along with this widespread use, however, comes key security measures that must take place in order to ensure the safety of your organization and data. This is particularly the case when receiving email information from previously unknown sources. These risks can include phishing attempts, malware, and other threats that can cause a negative impact to your business. Furthermore, when receiving an email address via account forms and user sign up information, you need to check that the information you are given is not only correct and real, but also that it does not lead to any malicious sources that could harm your organizational security.

The following APIs will allow you to instantly verify and validate an input email address without sending any kind of notification to the email user. This will help protect your organization in the event of any threats. The goal of this tutorial is to provide you with the tools to protect your organization’s information while providing a way to verify new accounts and user information.

This will be done through three separate functions. The first will analyze the validity of an email address’ syntax. The second will check for the address’ servers, and the third performs a full email address validation including returning the results for the previous two functions.

#java #api #java api #api access keys #api tutorial #email verification #email validation #java api tutorials #java apis #api tutorials

Samanta  Moore

Samanta Moore


How to Convert ODT Files to PDF in Java

Convert Office Open Document Text File (ODT) to standard PDF, DOCX, PNG, and JPG using Java.

Microsoft has maintained its position in the spotlight for formatted document creation and editing for good reason. Its extreme ease of use and lack of a learning curve has transformed the Microsoft Office Suite into a household name for most computer users in the United States as well as globally. This is propagated further through its almost ubiquitous use in education, as students are raised and taught using these applications.

The issue that arises with these programs, however, is their operation costs. For Apple and other non-Windows-based Operating Systems, the purchasing fees for Office can be steep. This, then, creates a paywall separating potential users from programs to which they are already accustomed. As an answer this problem, Microsoft created the OpenOffice application, which is a free, opensource version of the classic Office Suite. Within this application, you can perform almost all of the same functions as Office Suite, including creating text documents like one would with Microsoft Word. These text documents can be made using OpenOffice Writer, and are formatted using the .ODT file type. While this file type can be opened and saved using OpenOffice Writer and Word, in order to convert the file to a different format such as PDF you will need to run it through a conversion process.

The following APIs will allow you to convert your ODT documents to PDF, DOCX, PNG, and JPG for use in whatever way you need. The goal of this tutorial is to provide a simple and efficient means for instantly converting your ODT files without needing to find or download any extraneous programming.

#java #tutorial #api #pdf #java api #pdf converter #api access keys #api tutorial #java api tutorials #java apis

Joseph  Murray

Joseph Murray


Collection vs Collections in Java: Difference Between Collection & Collections in Java


This article will be looking into one of the most popular questions in Java Language – What is Collection in Java? Also, what do you mean by Collections in Java? Are Collection and Collections the same or different in Java?

What is Collection?

What is Collections?


#full stack development #collection #collection vs collections in java #collections in java #difference between collection and collections in java

Tyrique  Littel

Tyrique Littel


How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment

Samanta  Moore

Samanta Moore


Java Joy: Merge Maps Using Stream API

Maps, meet Stream. Merging made simple.

In Java, we can merge a key/value pair into a Map with the merge method. The first parameter is the key, the second the value, and the third parameter of the merge method is a remapping function that is applied when the key is already present in the Map instance. The remapping function has the value of the key in the original Map and the new value. We can define in the function what the resulting value should be. If we return null, the key is ignored.

If we want to merge multiple Map instances, we can use the Stream API. We want to convert the Map instances to a stream of Map.Entry instances, which we then turn into a new Map instance with the toMap method from the class Collectors. The toMap method also takes a remapping function when there is a duplicate key. The function defines what the new value is based on the two values of the duplicate key that was encountered. We can choose to simply ignore one of the values and return the other value. But we can also do some computations in this function, for example creating a new value using both values.

#java #tutorial #merge #java stream api #java 15 #java maps