简体   繁体   English

合并两个不同的列表一个是wifi类型的另一个是蓝牙类型的

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

The problem is simple yet generic.问题很简单但很笼统。 what i want to achieve is i want to make a list that will will be merge of two different lists one is of type Wifi and the other is of type bluetooth.我想要实现的是我想创建一个列表,该列表将合并两个不同的列表,一个是 Wifi 类型,另一个是蓝牙类型。

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

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

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

well as I've described in my code snippet this is what i want to achive.正如我在我的代码片段中描述的那样,这就是我想要实现的。 To merge two lists into one final result list.将两个列表合并为一个最终结果列表。 Can anybody guide me on this.任何人都可以指导我。 Thanks!谢谢!

What do the Wifi and bluetooth have in common and what are you going to use them for? Wifi 和蓝牙有什么共同点,你打算用它们做什么?

If they both have common functionality that you want to access then you could move it to an abstract class or interface and create a list of the interface instead.如果它们都具有您想要访问的通用功能,那么您可以将其移至抽象 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;
    }

}

If you are returning to a consumer then id suggest keeping them separate and having a Object that has fields for both lists.如果您要返回给消费者,那么 id 建议将它们分开并拥有一个包含两个列表字段的 Object。

class SearchDeviceResults {

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM