package com.unis.common.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @author qingsong.han
 * @description: 随机获取list中对象
 * @create 2024-06-03 12:02
 */
@Slf4j
public class RandomListElement {

    public static <T> T getRandomElement(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        Random rand = new Random();
        int index = rand.nextInt(list.size());
        log.info("RandomListElement index: {}", index);
        return list.get(index);
    }

    /*public static void main(String[] args) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("orgId", 1);
        map1.put("orgCode", "001");
        map1.put("orgName", "青海西宁-1粮库");
        mapList.add(map1);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("orgId", 2);
        map2.put("orgCode", "002");
        map2.put("orgName", "青海西宁-2粮库");
        mapList.add(map2);

        Map<String, Object> map3 = new HashMap<>();
        map3.put("orgId", 3);
        map3.put("orgCode", "003");
        map3.put("orgName", "青海西宁-3粮库");
        mapList.add(map3);
        Map<String, Object> randomElement = getRandomElement(mapList);
        log.info("mapList: {}", JSON.toJSONString(randomElement));
    }*/

}
