简体   繁体   中英

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.

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?

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 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.

class SearchDeviceResults {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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