Sunday, February 21, 2016

Java 8 Finding Specific Element in List with Lambda




As you probably know in Java 8 we can use Lambda expression for different manipulations with collections.
java8-lambda-expression

If you have a List with some custom objects inside and you want to find specific element in it you can use stream().filter procedure of Lambda instead of ForEach as you probably used to. Below is a simple example of this case.

List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);


So here we have filtered entire collection by specific condition. Notice that due to orElse(null) at the end of the expression if no file was found then Lambda will return null.


2 comments:

  1. What if one of those objects is another list with more custom objects ?

    like a tree structure. How can we travel trough the complete data structure ?

    ReplyDelete
  2. Nice tuts. Thanks for it.
    Java is hard to learn. I have to recognize that.
    Your tut helps me alot. thanks again.
    About me, i work at Savvycom, software outsourcing companies

    ReplyDelete