简体   繁体   English

android arraylist获取哈希图位置

[英]android arraylist get hashmap position

I have an ArrayList HashMap like the one below. 我有一个类似下面的ArrayList HashMap。

    ArrayList<HashMap<String, String>> mArrType = new ArrayList<>();

with the following values added into it 并添加以下值

    HashMap<String, String> map;

    map = new HashMap<String, String>();
    map.put("type", "TRIMMER");
    map.put("request", "5");
    map.put("actual", "0");
    mArrType.add(map);

    map = new HashMap<String, String>();
    map.put("type", "HAND ROUTER");
    map.put("request", "6");
    map.put("actual", "0");
    mArrType.add(map);

    map = new HashMap<String, String>();
    map.put("type", "AIR COMPRESSOR");
    map.put("request", "6");
    map.put("actual", "0");
    mArrType.add(map);

Question is how can i get the position of a hashmap from arraylist. 问题是如何从arraylist获取哈希图的位置。 eg : hashmap with 'type' trimmer has a position 0 in arraylist, I want to retrieve the position value "0" 例如:'type'修剪器的哈希图在arraylist中的位置为0,我想检索位置值“ 0”

I'll write a small util method 我会写一个小的util方法

private static int getTrimmerTypeMapPosition(ArrayList<HashMap<String, String>> mArrType) {
        for (int i = 0; i < mArrType.size(); i++) {
            HashMap<String, String> mp = mArrType.get(i);
            if (mp.get("type").equals("TRIMMER")) {
                return i;
            }    
        }    
        return -1;    
    }

To make this method very generic, have "type" and "TRIMMER" as method params, so that you can just pass any key and value pairs to check with. 为了使此方法非常通用,请将“类型”和“ TRIMMER”作为方法参数,以便您可以传递任何要检查的键和值对。

That's not efficiently possible with your data structure. 您的数据结构不可能有效地做到这一点。 You can either store the own position in each HashMap or loop through all entries and search for the one with the type you are looking for. 您既可以将自己的位置存储在每个HashMap也可以遍历所有条目并搜索您要查找的类型。

You can, of course, define another HashMap<String, Integer> which maps all your type strings to the corresponding ArrayList index. 当然,您可以定义另一个HashMap<String, Integer> ,它将所有类型的字符串映射到相应的ArrayList索引。

Others answer is also correct, but you can do this thing using Java8 also. 其他人的回答也是正确的,但是您也可以使用Java8来完成此操作。

Eg: 例如:

int index = IntStream.range(0, mArrType.size()).
                filter(i -> mArrType.get(i).get("type").equals("TRIMMER"))
                .findFirst().getAsInt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM