Using Lambda expression of Java 1.8 to simulate a SQL Like clause

Posted by Rajnilari2015 under Others category on | Points: 40 | Views : 2301
We all are familiar with the LIKE clause of ANSI SQL. If not please look into .Java 1.8 introduce the LAMBDA expression. Please read for an explanation about the same. In the following example, we will look into as how can we implement the LIKE clause of ANSI SQL in Java 1.8 by the help of LAMBDA expression.

import java.util.*;

public class LikeSimulationUsingLambda {

public static void main(String[] args){

//The initial collection
List<String> lstNames = new ArrayList<String>();

String nameToSearch = "N";

List<String> filterNames =
.stream() //Convert List to stream
.filter(name -> name.startsWith(nameToSearch)) //apply the search filter
.collect(Collectors.toList()); //convert Stream to List

//display the result
for(String name: filterNames) System.out.println(name);

} // end main

A Stream can be think of as a sequence of Data but Java 1.8 Streams is a new enter to the Java Collections API which works only with LAMBDA expression. Henceforth, first we converted the Collection (which is a list of string) into Streams. Then we apply the "filter" method for filtering the Stream. And finally by using the "collect" method, we collected the filtered streams and set it back from Streams to List.

The output
D:\Java\jdk1.8.0_45\bin>java LikeSimulationUsingLambda

Hope this will be helpful.

Comments or Responses

Login to post response