Java中用于保存存储桶列表ID的默认结构

问题描述 投票:1回答:1

我有以下代码

Map<Integer,int[]> mapa = new HashMap<Integer,int[]>();     
    int[][] idBlocoRef  = {
            {20,0,4,5,9,11,14},
            {2,3,7,8,17},
            {3,1,2,6,15,18,19}
    };      
    for (int i = 0; i < idBlocoRef.length; i++) {
        mapa.put(i,idBlocoRef[i]);
    }
    int[] aux;
    for (int chave : mapa.keySet()) {
        aux = mapa.get(chave);
        System.out.println("Bloco "+(chave+1)+" tem os valores");
        for (int i = 0; i < aux.length; i++) {
            System.out.print(aux[i]+",");
        }
        System.out.println();
    }

我想要的是在我的int数组中传递一个值并接收他所在的“桶”。例如:桶2中的ID 2,桶1中的ID 11,桶3中的ID 15 ......

我试过用HashMap这样做但是它没有正常工作。 Java中有任何自然结构可以帮我吗?

java arrays bucket id
1个回答
0
投票

使用int[]List<Integer>作为Map值并不重要,因为您将这些值视为只读,但是,通常建议使用List<Integer>,因为它提供了大量方法并且很容易进入Stream。 (别忘了关键的Integer0开始。)

Map<Integer, List<Integer>> map = new HashMap<>();  

for (int i = 0; i < idBlocoRef.length; i++) {
    map.put(i, Arrays.stream(idBlocoRef[i]).boxed().collect(Collectors.toList()));
}

好吧,Set<Integer>会更好,因为它不允许重复值,并且据我所知它适合您的用例(基于评论)。我看到你在2个“桶”中有id 23 - 我认为这是拼写错误,否则你必须定义行为,如果ID位于多个“桶”中。回到ID的唯一性:

Map<Integer, Set<Integer>> map = new HashMap<>();  

for (int i = 0; i < idBlocoRef.length; i++) {
    map.put(i, Arrays.stream(idBlocoRef[i]).boxed().collect(Collectors.toSet()));
}

现在让我们在一个桶中找到int idToFind = 3,这是返回的关键:

for (Entry<Integer, Set<Integer>> entry: map.entrySet()) {
    if (entry.getValue().contains(idToFind)) {
        System.out.println("The " + idToFind + " is in the bucket no. " + entry.getKey());
        break;
    }
}

如果您更喜欢Stream-API:

map.entrySet()
   .stream()
   .filter(e -> e.getValue().contains(idToFind))
   .findFirst()
   .ifPresent(e -> System.out.println("The " + idToFind + " is in the bucket no. " + e.getKey()));
© www.soinside.com 2019 - 2024. All rights reserved.