实现List<ServiceInstance>随机加权重获取一个实例对象
时间: 2024-12-11 19:32:51 浏览: 12
在Java中,如果你想从一个`List<ServiceInstance>`列表中随机选择一个实例,同时考虑到每个实例有不同的权重,你可以使用一种叫做“概率分布”的策略。这里通常会用到`Collections.shuffle()`方法配合自定义的一个`WeightedRandomProvider`来实现。
首先,你需要为每个`ServiceInstance`对象添加一个权重字段,并创建一个`WeightedRandom`类:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
class WeightedRandomProvider {
private List<WeightedItem<ServiceInstance>> items;
private Random random;
public WeightedRandomProvider(List<ServiceInstance> instances, int[] weights) {
this.items = new ArrayList<>();
for (int i = 0; i < instances.size(); i++) {
ServiceInstance instance = instances.get(i);
int weight = weights[i];
items.add(new WeightedItem<>(instance, weight));
}
random = new Random();
}
public ServiceInstance getRandom() {
Collections.shuffle(items, random);
return items.get(0).getElement();
}
private static class WeightedItem<T> {
private final T element;
private final int weight;
public WeightedItem(T element, int weight) {
this.element = element;
this.weight = weight;
}
public T getElement() {
return element;
}
public int getWeight() {
return weight;
}
}
}
```
然后,在需要的地方,你可以这样做来获取一个按照权重随机选择的服务实例:
```java
List<ServiceInstance> serviceInstances = ... // 获取服务实例列表
int[] weights = ... // 每个实例对应的权重数组
WeightedRandomProvider provider = new WeightedRandomProvider(serviceInstances, weights);
ServiceInstance selectedInstance = provider.getRandom();
```
阅读全文