Java中的 Map Values() 方法及示例
Map Values() 方法返回此映射中包含的值的集合视图。集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。
句法:
map.values()
参数:此方法不带任何参数。
返回值:它返回地图中所有值的集合视图。
示例 1:
Java
// Java program to illustrate the
// use of Map.Values() Method
import java.util.*;
public class GfG {
// Main Method
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map map
= new HashMap();
map.put(12345, "student 1");
map.put(22345, "student 2");
map.put(323456, "student 3");
map.put(32496, "student 4");
map.put(32446, "student 5");
map.put(32456, "student 6");
System.out.println(map.values());
}
}
Java
// Java program to illustrate the
// use of Map.Values() Method
import java.util.*;
public class GfG {
// Main Method
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map map
= new HashMap();
map.put(12345, "student 1");
map.put(22345, "student 2");
map.put(323456, "student 3");
map.put(32496, "student 4");
map.put(32446, "student 5");
map.put(32456, "student 6");
Collection collectionValues = map.values();
System.out.println("<------OutPut before modification------>\n");
for(String s: collectionValues){
System.out.println(s);
}
map.put(3245596, "student 7");
System.out.println("\n<------OutPut after modification------>\n");
for(String s: collectionValues){
System.out.println(s);
}
}
}
输出:
[student 4, student 3, student 6, student 1, student 2, student 5]
如您所见,上述示例的输出是返回值的集合视图。因此,地图中的任何更改都会自动反映在集合视图中。因此,请始终将集合的泛型与地图值的泛型相同,否则会出错。
示例 2:
Java
// Java program to illustrate the
// use of Map.Values() Method
import java.util.*;
public class GfG {
// Main Method
public static void main(String[] args)
{
// Initializing a Map of type HashMap
Map map
= new HashMap();
map.put(12345, "student 1");
map.put(22345, "student 2");
map.put(323456, "student 3");
map.put(32496, "student 4");
map.put(32446, "student 5");
map.put(32456, "student 6");
Collection collectionValues = map.values();
System.out.println("<------OutPut before modification------>\n");
for(String s: collectionValues){
System.out.println(s);
}
map.put(3245596, "student 7");
System.out.println("\n<------OutPut after modification------>\n");
for(String s: collectionValues){
System.out.println(s);
}
}
}
输出:
<------OutPut before modification------>
student 4
student 3
student 6
student 1
student 2
student 5
<------OutPut after modification------>
student 4
student 3
student 6
student 1
student 2
student 7
student 5