簡體   English   中英

如何檢查相同的ID,然后遞增該特定ID?

[英]How to check for the same ID, and then increment for that particular id?

我有一個hashmap,我們稱其為hashMap ,這是在一種方法中,我將傳入一個名為id的字符串。 我也有一個對象,我們稱它為UserObject 因此,當前我想做的就是使用以下代碼將輸出寫入csv文件:

for (UserObject user: hashMap.get(id)) {
            System.out.println(id);
            writer.println(id + "," + user.getTime() + "," + user.getLat() + "," + user.getLng()); // csv
        }

但是此ID可能是同一ID的倍數。 所以我想做的是,每當一個id用於for循環時,就會有一個計數器加一。 因此,當再次使用相同的ID時,增量將增加。 但是,當使用不同的ID時,這是另一個增量操作。 因此,基本上我的意思是,每當for循環運行時,我都要計算將運行相同ID的實例數。 我該怎么辦? 我似乎無法弄清楚邏輯。

PS System.out.print(id)是一行測試代碼,輸出是一個ID塊。

**編輯:該邏輯可以像SQL的count函數一樣工作,但是我沒有使用SQL,我只需要純Java語言就可以

不知道我是否正確理解它,但是如果您想對HashMap中的元素進行計數,則可以嘗試這樣的操作。

public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("1", "A");
    map.put("2", "B");
    map.put("3", "C");
    map.put("4", "B");
    map.put("5", "B");
    map.put("6", "C");

    System.out.println(count("B", map)); // output is 3
}

static int count(String id, Map<String, String> map) {
    int i = 0;
    for (String val : map.values()) {
        if (id.equals(val))
            i++;
    }
    return i;
}

編輯:如果您想包裝功能,每次您觸摸特定的值,計數器增加,您可以通過這種方法來實現。

public class IdHandler {

    Map<String, Integer> count = new HashMap<String, Integer>();

    public int count(String id) {
        return count.get(id);
    }

    public void export(Map<String, String> map) {
        for (String value : map.values()) {
            System.out.println(value);

            if (!count.containsKey(value)) {
                count.put(value, 1);
            } else {
                int i = count.get(value);
                count.put(value, ++i);
            }
        }
    }
}

public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("1", "A");
    map.put("2", "B");
    map.put("3", "C");
    map.put("4", "B");
    map.put("5", "B");
    map.put("6", "C");

    IdHandler id = new IdHandler();
    id.export(map);

    System.out.println(id.count("B")); // output is 3
    System.out.println(id.count("C")); // output is 2
}

暫無
暫無

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

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