รับผลิตภัณฑ์คาร์ทีเซียนหรือไม่?

ฉันมีสองรายการ:

List<Integer> partnerIdList;
List<Integer> platformIdList;

ฉันต้องได้ผลิตภัณฑ์คาร์ทีเซียนตามรายการเหล่านี้:

List<Pair<Integer, Integer> > partnerPlatformPairList;

โดยที่ Pair เป็นคลาสจากแพ็คเกจ org.apache.commons.lang3.tuple.Pair

ฉันจะทำอย่างนั้นได้อย่างไร? มีบางอย่างในไลบรารี apache-commons หรือไม่?


person St.Antario    schedule 18.05.2015    source แหล่งที่มา
comment
บางสิ่งตามแนว cartesianProduct ใน เอกสาร .guava-libraries.googlecode.com/git/javadoc/com/google/ อาจมีประโยชน์สำหรับคุณ   -  person Laurentiu L.    schedule 18.05.2015
comment
โปรดดูวิธีแก้ปัญหาที่คล้ายกัน: [Cartesian product of List of Lists in Java][1] [1]: stackoverflow.com/questions/9591561/   -  person Balkrishan Aggarwal    schedule 18.05.2015


คำตอบ (2)


หากคุณไม่ต้องการใช้โซลูชันภายนอก ไลบรารี คุณสามารถเขียนโค้ดเวอร์ชันของคุณเองได้:

public static <T, U> List<Pair<T, U>> cartesianProduct(List<T> list1, List<U> list2) {
    List<Pair<T, U>> result = new ArrayList<>();
    for (T el1: list1) {
        for (U el2 : list2) {
            result.add(Pair.of(el1, el2));
        }
    }
    return result;
}
person Dmitry Ginzburg    schedule 18.05.2015

มีโค้ด github คุณสามารถดูมันได้ โดยพื้นฐานแล้วมันจะรัน for-loop ตามจำนวนรายการและจำนวนรายการ มันจะลดความพยายามในการเขียนโค้ดของคุณ แต่พื้นฐานยังคงเหมือนเดิม

or

ใช้รหัสต่อไปนี้

for (int i = 0; i < partnerIdList.size(); i++)
        for (int j = 0; j < platformIdList.size(); j++)
            partnerPlatformPairList.add(new Pair<Integer, Integer>(partnerIdList.get(i), platformIdList.get(j)));
person Abhishek    schedule 18.05.2015