简体   繁体   中英

Iterating through multiple lists using single for-each loop in java

I have multiple lists created like below

static List<String> dbName = new ArrayList<String>();
    static List<String> dbServerName = new ArrayList<String>();
    static List<String> lDbName = new ArrayList<String>();
    static List<String> lServerName = new ArrayList<String>();
    static List<String> serverName = new ArrayList<String>();
    static List<String> dbServerNameSecondary = new ArrayList<String>();

is it possible to iterate over all the list objects using a single for-each loop like below

for (items in dbName,dbServerName....)

I would like to iterate parallely and put the values obtained in the below query

String drop = "Drop table if exists "+hive_db+"."+"IB_C3_"+dbName+"_"+dbServerName;

Yes, assuming the lists are all the same size , you can iterate them in parallel by using a standard for loop:

static List<String> dbName = new ArrayList<String>();
static List<String> dbServerName = new ArrayList<String>();
static List<String> lDbName = new ArrayList<String>();
static List<String> lServerName = new ArrayList<String>();
static List<String> serverName = new ArrayList<String>();
static List<String> dbServerNameSecondary = new ArrayList<String>();

// code filling lists here

for (int i = 0; i < dbName.size(); i++) {
    // dbName.get(i)
    // ...
    // dbServerNameSecondary.get(i)
}

However, if the lists are the same size, then using the Object-Oriented features of Java is strongly recommended. This means creating a class for the values.

public class Database {
    private String dbName;
    private String dbServerName;
    private String lDbName;
    private String lServerName;
    private String serverName;
    private String dbServerNameSecondary;
    // getters and setters here
}

static List<Database> databases = new ArrayList<>();

// code filling list here

for (Database database : databases) {
    // database.getDbName()
    // ...
    // database.getDbServerNameSecondary()
}

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