简体   繁体   中英

How to create a single 3 element collection list using three foreach loop in JAVA.?

I want to create a single list which consist 3 elements, each one get value from 3 different foreach loop.

 for (WebElement webElement : li) {
        key = webElement.getText().trim().substring(10, 16) ;
  }
 //e.g {1,2,3,4,5,.......1000}

 for (String string : defectidList) {
        defectid =string;
  }
 //e.g {abc-1,abc-2,abc-3,abc-4,abc-5,......1000}
 for (WebElement element : hreflist) {
        hreflink =element.getText();
  }
 //e.g. {abc.com,bcd.com,def.com,abc.com,bcd.com,....1000}

 Class Pair{
  String key;
  String defectid;
  String hreflinks;

  Pair(String k,String d, String h){
  this.key=k;
  this.defectid=d;
  this.hreflinks=h;
  }
 }
ArrayList<Pair> pairlist = new ArrayList<Pair>
Pair p = new Pair(key,defectid,hreflinks)    
pairlist.add(p) 

How i should add each element from each loop so that i should get pairlist as

1 abc-1 abc.com
2 abc-2 bcd.com
3 abc-3 def.com
4 abc-4 abc.com
5 abc-5 bcd.com

if the size of three lists are same, you could try omething like

for(int i=0;i<li.size();i++){
    ...
        Pair p = new Pair(
                li.get(i).getText().trim().substring(10, 16),
                defectidList.get(i),
                hreflink.get(i).getText()
                );
    ...
}

Null case handling ignored.

How about a normal for loop?

ArrayList<Pair> = new ArrayList<Pair>;
for(int i = 0; i < li.length && i < defectidList.lengh && i < hrefList.length; i++){
    String key = li[i].getText().trim().substring(10, 16);
    String hrefLink = hrefList[i].getText();
    pairList.add(new Pair(key, defectidList[i], hrefLink));
}

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