繁体   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