簡體   English   中英

java:檢查HashMap值中是否存在對象的屬性

[英]java: check if an object's attribute exists in HashMap values

我有一個HashMap,其類型為Double ,我的自定義對象為value 看起來像這樣:

private static Map<Double, Incident> incidentHash = new HashMap<>();

Incident對象具有以下屬性: String dateString addressString incidentType

現在,我有一個從用戶那里得到的String date作為輸入,我想檢查在HashMap中是否存在任何使用該用戶輸入日期的事件。 給定日期的HashMap中可以有很多事件,但是只要給定日期至少有一個事件,我就可以做某事

我可以遍歷HashMap中的所有值並檢查是否存在給定的日期,但是我想知道是否存在不修改數據結構的更好,更有效的方法。

您可以使用流API(來自Java8),如以下代碼所示,並帶有內聯注釋:

String userInput="10-APR-2017";

Optional<Map.Entry<Double, Incident>> matchedEntry = 
  incidentHash.entrySet().stream().
  //filter with the condition to match
  filter(element -> element.getValue().getDate().equals(userInput)).findAny();

 //if the entry is found, do your logic
 matchedEntry.ifPresent(value -> {
            //do something here
 });

如果您正在尋找JDK1.8之前的版本,則可以參考以下代碼:

String userInput="10-APR-2017";
Set<Map.Entry<Double, Incident>> entries = incidentHash.entrySet();
Map.Entry<Double, Incident> matchedEntry = null;
for(Iterator<Map.Entry<Double, Incident>> iterator = entries.iterator(); 
                    iterator.hasNext();) {
    Map.Entry<Double, Incident> temp = iterator.next();
    if(temp.getValue().getDate().equals(userInput)) {
        matchedEntry = temp;
        break;
    }
}

給定您的HashMap, ,沒有其他方法可以對HashMap進行迭代

至於更改結構,您可以將Map<String, List<Incident>>用作方法,這樣就可以將date作為鍵,並根據需要設置該日期的事件ListThere can be many Incidents in the HashMap with the given date

所以這將是O(1)

 //considering that the key is added when you have at least one incident
 if (yourHash.get("yourDateStringWhatEverTheFormatIs") != null)

您可以將TreeMap與自定義Comparator一起使用 在比較器中比較日期的值。

您將不得不遍歷地圖,直到找到匹配的數據。 由於您只需要知道是否存在任何事件,您可以在找到匹配項時直接退出循環,而無需遍歷地圖的其余部分。

您只能保留第二個將屬性與對象匹配的Hash / TreeMap,因此您也可以快速檢查此屬性。 但是,您必須為要快速訪問的每個屬性創建一個這樣的映射。 這使它更加復雜並使用更多的內存,但速度可能要快得多。

如果這不是一個選擇,則在其他答案中引用的流API是一種迭代所有對象以搜索屬性的好方法。

private static Map<Double, Incident> incidentHash = new HashMap<>();
private static Map<String, List<Incident>> incidentsPerDayMap = new HashMap<>();

鑒於您不想iterate Map,並且當前它是獲取所需值的唯一方法,因此我建議您重新推薦另一個包含Date作為鍵和List<Incident>作為值的Map 它可以是TreeMap ,例如:

Map<Date, List<Incident>> incidents = new TreeMap<>();

你可以put這個入口Map ,每當項被添加到原來的Map ,例如:

Incident incident = ;// incident object
Date date; //Date
incidents.computeIfAbsent(date, t -> new ArrayList<>()).add(incident);

用戶輸入Date ,您可以僅通過incidents.get()獲取屬於該日期的所有事件。 盡管這將為您提供一個list並且您仍然需要對其進行迭代,但是它將包含更少的元素,並且TreeMap get方法將確保您在排序時log n復雜性。 因此,您的搜索操作將更加高效。

暫無
暫無

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

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