網頁

2019/12/14

Java 函數(方法)整合問題

IT邦幫忙看到的問題,以下兩個函數,能整合為一個嗎?

public List<String> getRandom1Ary(ArrayList<ExamItemsBean> items, int count)
{
    List<String> resultAry = new ArrayList<String>();
    Random random = new Random();
    do
    {
        int next = random.nextInt(items.size());
        ExamItemsBean item = items.get(next);
        if (!resultAry.contains(item.getAA())) // <-- 差異
        {
            resultAry.add(item.getAA()); // <-- 差異
        }
    } while (resultAry.size() < count);
    return resultAry;
}

public List<String> getRandom2Ary(ArrayList<ExamItemsBean> items, int count)
{
    List<String> resultAry = new ArrayList<String>();
    Random random = new Random();
    do
    {
        int next = random.nextInt(items.size());
        ExamItemsBean item = items.get(next);
        if (!resultAry.contains(item.getBB())) // <-- 差異
        {
            resultAry.add(item.getBB()); // <-- 差異
        }
    } while (resultAry.size() < count);
    return resultAry;
}

上面方法設計的問題在於,不應該傳入ArrayList<ExamItemsBean>這一大包東西而只是為了隨機取得其中的機個元素,應該只需要傳入要隨機取得的元素就好了。

package com.abc.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        ArrayList<ExamItemsBean> items = new ArrayList<>();

        List<String> aaList = items.stream().map(ExamItemsBean::getAA)
                .collect(Collectors.toList());
        
        List<String> bbList = items.stream().map(ExamItemsBean::getBB)
                .collect(Collectors.toList());

        int count = 5;
        List<String> randomAry1 = getRandomAry(aaList, 5);
        List<String> randomAry2 = getRandomAry(bbList, 5);
    }

    public static <E> List<E> getRandomAry(List<E> list, int count) {
        if (list == null || list.size() < 1 || count < 1) {
            return new ArrayList<E>();
        }

        List<E> arr = new ArrayList<E>();
        Random random = new Random();
        do {
            int next = random.nextInt(list.size());
            E e = list.get(next);
            if (!arr.contains(e)) {
                arr.add(e);
            }
        } while (arr.size() < count);
        return arr;
    }

}

我猜發問者應該是在博弈業要抽卡或抽老虎機圖案之類的吧。


參考:

沒有留言:

張貼留言