簡體   English   中英

按多個值執行搜索 - 使用 arrayList object

[英]Performs a search by multiple values - using an arrayList object

我對 java 有一個問題,我已經嘗試解決了幾個小時但無法解決。

我有一個廣告的 object,我將這個 object 與 arrayList 一起使用。 I want to select the object of Ad - which are inside the arrayList - I want to select the object according to its attributes, I do this in the function: I get attributes that an ad object has - I want to filter the Ad by attributes .

public class filterAds {
public class Ad {
        String domain;
        String role;
        String area;

        public Ad(String domain, String role, String area) {
            this.area = area;
            this.domain = domain;
            this.role = role;
        }
    }

    List<Ad> adList = new ArrayList<Ad>();

    public String[] getAds(String role, String domain, String area) {

        boolean filter = true;
        if(role != null)
        {
            //use it in search
        }
        if(area != null)
        {
            //use it in search
        }
        if(domain != null)
        {
            //use it in search
        }
        
        List<String> adIDsList = new ArrayList<String>();
        for (int i = 0; i < adList.size(); i++) {
            if (filter /* && also other conditions*/) {
                adIDsList.add(adList.get(i).id);
            }
        }
        
        String[] adIDs = new String[adIDsList.size()];;
        adIDs = adIDsList.toArray(adIDs);
        
        return adIDs;
}
}

我認為問題不大,只需要修復 if 條件 - 但我幾個小時都無法解決。

組織此類搜索的標准方法是:

List<String> adIDsList = new ArrayList<String>();
for (int i = 0; i < adList.size(); i++) {
    Ad ad = adList.get(i);
    if (
        (role == null || role.equals(ad.role)) &&
        (area == null || area.equals(ad.area)) &&
        (domain == null || domain.equals(ad.domain))
    ) {
        adIDsList.add(ad.id);
    }
}

所以,我們在相同的條件下處理 null 和非空

您可以使用 stream api 從列表中過濾數據。 下面是粗略的代碼,可以讓您了解如何做。

List<String> adIDsList = adList.stream()
.filter(ad -> role.equals(ad.role))
.filter(ad -> domain.equals(ad.domain))
.filter(ad -> area.equals(ad.area))
.map(Ad::id)
.collect(Collectors.toList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM