2017-10-05 57 views
2

我被困在下面的問題:使用番石榴Sets.cartesianProduct的未知數量的參數

我有這樣定義的項目的動態列表:

List<Object> itemList = ArrayList(ArrayList<Object1, Object2, Double[]>) 

Object1Object2是這裏不感興趣,但數組Double[]包含任意數量的條目。

在我的代碼中,我遍歷外部ArrayList並嘗試計算番石榴的cartesianProduct。到現在我有這樣的事情(部分不工作的代碼,對不起......):

private Set<List<Set<Double>>> getValueCombinations() { 
    List<Set<Double>> valuesOfInnerArrays = new ArrayList<>(); 
    // Loop over the list of device data sets in the class and add the trim value vectors to a list for further 
    // processing and cartesian prooduct generation. 
    for (Integer indexCounter = 0; indexCounter < OuterArrayList.size(); indexCounter++) { 
     final List<Object> innerDataSet = (List<Object>) OuterArrayList.get(indexCounter); 
     final Set<Double> innerDoubleArray = ImmutableSet.of(((List<Double>) innerDataSet.get(2)).toArray(new Double[])); 
     valuesOfInnerArrays.add(innerDoubleArray); 
    } 
    ImmutableList<Set<Double>> test = ImmutableList.of(valuesOfInnerArrays) 
    // generate Cartesian product of all trim vectors = a n x m matrix of all combinations of settings 
    final Set<List<Set<Double>>> cartesianProduct = Sets.cartesianProduct(ImmutableList.of(valuesOfInnerArrays)); 

    return cartesianProduct; 
} 

在我發現所有的例子,他們總是叫笛卡兒積與已知的設置,這是我不能做:

Set<Double> first = ImmutableSet.of(1., 2.); 
Set<Double> second = ImmutableSet.of(3., 4.); 
Set<List<Double>> result = 
Sets.cartesianProduct(ImmutableList.of(first, second)); 

我最後想要的是存儲在內部Double []數組中的所有數字的聯合。

任何幫助表示讚賞。

回答

2

感謝the Post "Java Guava CartesianProduct"我解決了我的問題。我的最終解決方案是這樣的:

private Set<List<Double>> getValueCombinations() { 
    final List<Set<Double>> valuesOfInnerArrays = new ArrayList<>(); 
    // Loop over the list of device data sets in the class and add the value vectors to a list for further 
    // processing and cartesian product generation. 
    for (Integer indexCounter = 0; indexCounter < outerArrayList.size(); indexCounter++) { 
     final List<Object> innerDataSet = (List<Object>) deviceDataSets.get(indexCounter); 
     final SortedSet<Double> >innerDoubleArray = new TreeSet<>((List<Double>) innerDataSet.get(2)); 
     valuesOfInnerArrays.add(innerDoubleArray); 
    } 

    return Sets.cartesianProduct(valuesOfInnerArrays); 
} 

此外,我改變了我的輸入列表的格式:

List<Object> itemList = ArrayList(ArrayList<Object1, Object2, List<Double>>)