在Java中使用Map Values() Method的例子
Map Values()方法返回Collection视图,包含在此Map中包含的所有值。 较集合由Map支持,因此对Map的更改将反映在集合中,反之亦然。
语法:
map.values()
参数: 此方法不接受任何参数。
返回值: 它返回Map中所有值的Collection视图。
实例1:
//Java程序说明
//使用Map.Values() Method
import java.util.*;
public class GfG {
//主方法
public static void main(String[] args)
{
//初始化HashMap类型的Map
Map<Integer, String> map
= new HashMap<Integer, String>();
map.put(12345, "学生1");
map.put(22345, "学生2");
map.put(323456, "学生3");
map.put(32496, "学生4");
map.put(32446, "学生5");
map.put(32456, "学生6");
System.out.println(map.values());
}
}
输出:
[student 4, student 3, student 6, student 1, student 2, student 5]
如您所见,上面例子的输出返回了值的集合视图。因此,在Map中进行的任何更改都会自动反映在集合视图中。因此,始终将集合的泛型相同作为Map的值的泛型,否则会报错。
实例2:
// 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<Integer, String> map
= new HashMap<Integer, String>();
map.put(12345, "学生1");
map.put(22345, "学生2");
map.put(323456, "学生3");
map.put(32496, "学生4");
map.put(32446, "学生5");
map.put(32456, "学生6");
Collection<String> collectionValues = map.values();
System.out.println("<------ 修改前的输出 ------>\n");
for(String s: collectionValues){
System.out.println(s);
}
map.put(3245596, "学生7");
System.out.println("\n<------ 修改后的输出 ------>\n");
for(String s: collectionValues){
System.out.println(s);
}
}
}
输出:
<------ 修改前的输出 ------>
student 4
student 3
student 6
student 1
student 2
student 5
<------ 修改后的输出 ------>
student 4
student 3
student 6
student 1
student 2
student 7
student 5
极客教程