我有以下代码
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中有任何自然结构可以帮我吗?
使用int[]
或List<Integer>
作为Map
值并不重要,因为您将这些值视为只读,但是,通常建议使用List<Integer>
,因为它提供了大量方法并且很容易进入Stream
。 (别忘了关键的Integer
从0
开始。)
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 2
和3
- 我认为这是拼写错误,否则你必须定义行为,如果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()));