簡體   English   中英

合並兩個不同的列表一個是wifi類型的另一個是藍牙類型的

[英]merge two different lists one is of wifi type other is of bluetooth type

問題很簡單但很籠統。 我想要實現的是我想創建一個列表,該列表將合並兩個不同的列表,一個是 Wifi 類型,另一個是藍牙類型。

List<WifiModel> wifiList = [new WifiModel(), new WifiModel()]

List<Bluetooth> bluetoothList = [new BluetoothModel(), new BluetoothModel()]

List<ResultModel> result = [new WifiModel(), new BluetoothModel(), new WifiModel()]

正如我在我的代碼片段中描述的那樣,這就是我想要實現的。 將兩個列表合並為一個最終結果列表。 任何人都可以指導我。 謝謝!

Wifi 和藍牙有什么共同點,你打算用它們做什么?

如果它們都具有您想要訪問的通用功能,那么您可以將其移至抽象 class 或接口並創建接口列表。

class Scratch {

    public static void main(String[] args) {
        List<Bluetooth> bluetoothList = new ArrayList<>();
        bluetoothList.add(new Bluetooth());

        List<Wifi> wifiList = new ArrayList<>();
        wifiList.add(new Wifi());

        List<Connectable> connectables = new ArrayList<>();
        connectables.addAll(bluetoothList);
        connectables.addAll(wifiList);

        connectables.forEach(item -> item.connect());

        System.out.println("Finished");
    }

}

class Bluetooth extends Connectable {

}

class Wifi extends Connectable {

}

abstract class Connectable {

    public boolean connect(){
        System.out.println("Connected");
        return true;
    }

}

如果您要返回給消費者,那么 id 建議將它們分開並擁有一個包含兩個列表字段的 Object。

class SearchDeviceResults {

    List<Bluetooth> yada....
    List<Wifi> tada....

}

暫無
暫無

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

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