2016-04-26 18 views
1

我正在開發一個項目,我必須確定駕駛事件何時結束。一個函數被賦予一個HashMap<Date, Integer>,其中包含車輛/步行的置信水平,與unix時間戳一起以百分比的形式。Java HashMap迭代尋找驅動結束事件

我正試圖迭代這個HashMap,確定一個駕駛事件是否已經結束。

我是一名PHP開發人員,使用這樣的Java邏輯是一個真正的挑戰,我努力實現一些應該很簡單的事情。任何幫助讚賞。

繼承人的邏輯,我想實現:

If 
    we have at least 1 minute worth of data with 10 items in our HashMap 
then 
    loop HashMap 
    if past 30 seconds of time, from 30 seconds ago contain driving data of 60% confidence adverage or above then 
    AND past 30 seconds of time from now contains working data with average 60% confidence or above 
    then 
     mark isDriving as true 
if isDriving == true 
then 
    doSomething()` 

我的HashMap中看起來是這樣的:

private HashMap mActivityData = new HashMap<String, Long>(); 

mActivityData.putExtra("in_vehicle",80); // % confidence 
mActivityData.putExtra("on_foot",10); // % confidence 
mActivityData.putExtra("time",1461684458); // unix time stamp 
+1

讓您的仿製藥正確使用,例如對於顯示的數據:'private HashMap mActivityData = new HashMap <>();' –

+0

實際上,如果值是不同的類型(%vs timestamp),那麼Map在這裏看起來不正確。假設您不需要動態創建新的密鑰,只需使用三個正確類型的變量:'double in_vehicle; double on_foot;日期時間;'。 –

+1

你的問題到底是什麼?你有什麼嘗試,哪裏失敗? –

回答

1

這僅是部分答案。

你已經在你的問題中提到了「循環HashMap {...}」,但是你只能遍歷hashmap的鍵。 (以上用.values()值)

爲了得到一個HashMap<Date, Integer>的鍵:

Set<Date> dates_unordered = my_hashmap.keySet(); 

一組是無序的,要責令其使用功能,像this one創建一個有序列表。 (「日期」類實現是需要的整理工作的「可比」接口)

List<Date> dates_ordered = asSortedList (dates_unordered); 

遍歷列表。

Iterator<Date> it = dates_ordered.iterator(); // create an iterator object 
while (it.hasNext()) 
{ 
    Date d = it.next(); 
    Integer i = my_hashmap.get (d); // access value in hashmap with this key 

    // do something with "i" here 
    // ... 
} 
+0

這很棒,解決了我的問題。感謝您的好解釋。 – kirgy