Home > front end >  How to check if list has more then 3 elements using Java8
How to check if list has more then 3 elements using Java8

Time:12-16

I have a method that accepts a list of object.

I want to iterate through that list and check if the list has more than 3 elements. If it does, I want to throw error You can only add 3 elements

If not, I want to save those elements in database.

I want to use Java 8 streams in this case.

So far I have this code:

public List<MyObject> addMyObject(List<MyObject> myObject) {

        if(playingStyle.isEmpty()){
        throw new IllegalArgumentException("object cannot be null");
        }

        return myObject.stream()
                .limit(3)
                .map( ps -> {
                    try {
                        return repository.save(new MyObject(ps.getName(), ps.getAverage(), ps.getPriority()));
                    } catch (Exception e) {
                        log.warn("MyObject fields not correct {} {}", ps, e.getMessage());
                        throw e;
                    }
                }).collect(Collectors.toList());
    }

I have tried to use .limit() but what it does is it takes first 3 objects (if I have sent in 4) and saves them, last one just forgets.

What I am trying to achieve is if list is empty return error, if list size is bigger than 3 return error, but using Java 8.

CodePudding user response:

Something like this?

public List < MyObject > addMyObject(List < MyObject > myObject) {

    if (playingStyle.isEmpty()) {
        throw new IllegalArgumentException("playingStyle cannot be null");
    }

    if (myObject.size() > 3)
        throw new IllegalArgumentException("You can only add 3 elements");

    return myObject.stream()
        .limit(3)
        .map(ps -> {
            try {
                return repository.save(new MyObject(ps.getName(), ps.getAverage(), ps.getPriority()));
            } catch (Exception e) {
                log.warn("MyObject fields not correct {} {}", ps, e.getMessage());
                throw e;
            }
        }).collect(Collectors.toList());
}

Also, I would change repository.save(new MyObject(ps.getName(), ps.getAverage(), ps.getPriority())); to repository.save(ps);

CodePudding user response:

For a List just check the size property.

For a Stream, you can do:

import java.util.*;
import java.util.stream.*;

class Main {
    
    private static Boolean hasThreeOrMoreElements(final Stream s) {
        return s.limit(3).count() >= 3;
    }
    
    public static void main(String[] args) {
        System.out.println(hasThreeOrMoreElements(Arrays.asList(1).stream()));
        System.out.println(hasThreeOrMoreElements(Arrays.asList(1, 2).stream()));
        System.out.println(hasThreeOrMoreElements(Arrays.asList(1, 2, 3).stream()));
        System.out.println(hasThreeOrMoreElements(Arrays.asList(1, 2, 3, 4, 5, 6).stream()));
    }
}
  • Related