之间生成随机数的方法
我正在尝试使用下面的方法生成随机列,在生成列之后,我在我的SELECT sql
中使用这些列。
final String columnsList = getColumns(table.getColumns());
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, " + columnsList + " from " + table.getTableName() + " where id = ?";
/**
* A simple method to get the column names in the order in which it was
* inserted
*
* @param columns
* @return
*/
private String getColumns(final List<String> columns) {
List<String> copy = new ArrayList<String>(columns);
Collections.shuffle(copy);
int rNumber = random.nextInt(columns.size());
List<String> subList = copy.subList(0, rNumber);
Collections.sort(subList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
}
});
return StringUtils.join(subList, ",");
}
问题陈述:-
有时我看到columnsList
值是空的,如果它是空的,那么selectSql
将无法工作,因为在from keyword
之前会有额外的,
。如何确保getColumns
每次至少返回一个条目?
我相信nextInt
会在0 (inclusively) and n (exclusively)
之间产生随机数。所以有时它可能会选择0,任何在1(inclusively) and n (exclusively)
一种方法是:
return subList.isEmpty() ? "1" : StringUtils.join(subList, ",");
但我认为更好的是修改selectSql
为
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE " + columnsList + " from " + table.getTableName() + " where id = ?";
然后
return subList.isEmpty() ? "" : ","+StringUtils.join(subList, ",");
如果你想从随机中得到至少一个值,你也可以这样做:
int rNumber = 1+random.nextInt(columns.size()-1);