Find an element in a list using Java 8 Stream API
Finding an element in a list is very common task that you may encounter during java programming. This sneppet will teach you how to find an element in list using Java 8 Stream API feature.
1. Define Task POJO:
Define Task POJO class as shown below
package com.sneppets.java; public class Task { private int taskId; private String taskName; private int baseDuration; //in hours public Task(int taskId, String taskName, int baseDuration) { this.setTaskId(taskId); this.setTaskName(taskName); this.setBaseDuration(baseDuration); } public int getTaskId() { return taskId; } public void setTaskId(int taskId) { this.taskId = taskId; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public int getBaseDuration() { return baseDuration; } public void setBaseDuration(int baseDuration) { this.baseDuration = baseDuration; } }
2. Find an element in a list using Java 8 Stream API
You can use Java 8 Stream API to find an element in a list. First you need to create list (tasklist) as shown in the example below. And invoke stream() method on the tasklist as shown in findTask() method in the below example. Then call the filter() method with proper predicate (activityId) based on which you wanted to find an element in the list.
Finally call findAny() which returns the first element that matches the filter results if there exists a match. You can default to null if there are no matches, but this is optional.
package com.sneppets.java; import java.util.ArrayList; import java.util.List; public class TaskTest { public static void main (String[] args){ //create tasklist List<Task> taskList = new ArrayList<>(); createTaskList(taskList); //find task based on taskName/ activityid String activityId = "VoiceServiceSetup"; Task task = findTask(activityId, taskList); System.out.println("taskId: " + task.getTaskId() + ", taskName: " + task.getTaskName() + ", baseDuration: " + task.getBaseDuration()); } private static void createTaskList(List<Task> taskList) { taskList.add(new Task(1,"DataServiceSetup",2)); taskList.add(new Task(2,"VoiceServiceSetup",4)); taskList.add(new Task(3,"PatchInstallation",1)); } private static Task findTask(String activityId, List<Task> taskList) { Task task0 = taskList.stream() .filter(task -> activityId.equals(task.getTaskName())) .findAny() .orElse(null); return task0; } }
Output
taskId: 2, taskName: VoiceServiceSetup, baseDuration: 4
Further Reading
- Java ArrayList removeAll() method not removing elements
- Java program to check if string is not empty and not null
- How to add new field in an existing Mongo DB collection document
- How to manually install JAR dependency in local repository using maven