Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of stream instead of for loop in java 8

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.12k
    Comment on it

    We all know about the use of For loop and for each loop that is used to iterate all elements in list or collection but some time in case of n numbers of items loop traverse till nth item that is time consuming but after java 8 we have some strong and faster functional operations over collections named Stream. Stream is basically provide fast operation on collections like to filter or search some data.

    Here we have an example to search a assest location "delhi" over collection using for loop and using stream.

    For loop to find the required data :

    public class Asset implements Serializable {
    
        public String assestType;
        public String assestLocation;
        public String assestValue;
    
        public String getAssestLocation() {
            return assestLocation;
        }
    
        public String getAssestValue() {
            return assestValue;
        }
    
        public void setAssestValue(String assestValue) {
            this.assestValue = assestValue;
        }
    
        public void setAssestLocation(String assestLocation) {
            this.assestLocation = assestLocation;
        }
    
        public String getAssestType() {
            return assestType;
        }
    
        public void setAssestType(String assestType) {
            this.assestType = assestType;
        }
    }

    Now using for loop to find item :

    public List<Asset> getAllAssests() {
    
        List<Asset> result = new ArrayList<>();
    
        for (Asset assest : assets) {
            if (assest.getAssestLocation().contains("delhi")) {
                result.add(assest);
            }
        }
    
        return result;
    }

    now using Stream Api :

    public List<Asset> getAllAssests() {
        return assest.stream()
                .filter(assest -> assest.getTags().contains("delhi"))
                .collect(Collectors.toList());
    }
    

    using filter method of stream we can easily filter out required item.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: