简体   繁体   English

如何从流中获取随机对象并将其返回

[英]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. 我有一些来自Google的用户的列表,现在在流中,我说给每个Google用户都新建一个HRVacationUser(女巫是模型),然后给我(他们的电子邮件,一些随机日期,一些随机日期),该随机日期用于随机假期。 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? 如何从Google用户那里获取随机用户并设置假期的随机日期,以便我可以在数据库中发出请求-给我这个正在假期的用户?

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 我的列表/ GoogleUser>的大小例如为80,我只想为随机用户设置空缺日期,然后向if(用户处于空缺状态返回'user')发出请求,并在数据库中进行请求以给我假期用户

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 =) 随机元素的更多可能解决方案在这里 =)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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