简体   繁体   中英

How to get random objects from a stream and return it

I have List with some users from google and now in stream I say for every google user make new HRVacationUser ( witch is model ) and give me ( their email, some random date, some random date ) which random date is for random holiday. But in that case i set each user is on vacantion. How can I take random user from google users and set random date for holiday, so I can make a request in the database - give me this user which is in holiday?

My List /GoogleUser> is with size for example 80, and I want to set only for random users vacantion date, and then to make request if(user is in vacantion return 'user') and in database to do request give me holiday users

public List<HRVacationUser> listVacationGoogleUsers(List<GoogleUser> allGoogleUsers){
        LocalDate date = LocalDate.now();
        List<HRVacationUser> collectHRUser = allGoogleUsers.stream()
                .map(user ->
                        new HRVacationUser(user.getPrimaryEmail(), date.minusDays(ThreadLocalRandom.current().nextInt(1,5)), date.plusDays(ThreadLocalRandom.current().nextInt(1, 5))))
                .collect(toList());
        return collectHRUser;
    }

You can take a random item from your list, based on your list size:

import java.util.Random;

List<?> yourList = new ArrayList<>();
yourList.get(new Random().nextInt(yourList.size()));

you can use the random library

import java.util.Random;

More possible solutions for random elements here =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM