簡體   English   中英

如何比較 Java 中的兩個列表並根據每個組合打印結果?

[英]How do I compare two lists in Java and print the result based on each combination?

我想根據價格矩陣計算每個車站之間的票價:

        a  b c 

  a     0  2 3
  b     4  0 1
  c     7  2 0

示例:根據上述價格矩陣中的值, from a to b打印2from c to a打印7

就是這樣,我想根據兩個站點列表打印火車票票價:“from:”列表和“to:”列表。 我想在比較后打印票價。 每種組合都有固定票價。 例如a站到b站,票價是10。對於任何一個站到另一個站,都有固定的票價。

我將創建一個 class,它負責存儲票價。

public class FareStorage {
    Map<TownCombination, Double> fares;

    //...

    public double getFare(String townA, String townB) {
        return fares.get(new TownCombination(townA, townB));
    }

    public void addFare(String townA, String townB, double fare) {
        fares.put(new TownCombination(townA, townB));
    }

    class TownCombination {
        String town1;
        String town2;

        //If a fare from A to B is equals the fare from B to A, 
        //then the A-B and the B-A combinations should be equal. 
        //Override hashCode and equals the way you want.  
    }
}

它不完整,但我希望你能明白。 這是您可以使用它的方式:

        FareStorage storage = new FareStorage();
        storage.addFare("A", "B", 10.2);

        //....
        double fare = storage.get("A", "B");

你也可以使用番石榴的Table

示例:

Table<Integer, String, String> table = HashBasedTable.create();
table.put(1, "a", "1a");
table.put(1, "b", "1b");
table.put(2, "a", "2a");
table.put(2, "b", "2b");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM