1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Java遍历Map集合的五种方法

Java遍历Map集合的五种方法

时间:2021-02-14 00:44:36

相关推荐

Java遍历Map集合的五种方法

public static void main(String[] args) {Map<String, String> map = Maps.newHashMap();map.put("a", "1");map.put("b", "2");map.put("c", "3");// 方法一 IteratorSystem.out.println("迭代器");Iterator it = map.entrySet().iterator();while (it.hasNext()) {Map.Entry entry = (Map.Entry) it.next();System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());}// 方法二 entrySetSystem.out.println("entrySet");for (Map.Entry<String, String> entry : map.entrySet()) {System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());}// 方法三 keySetSystem.out.println("entrySet");for (String s : map.keySet()) {System.out.println("key=" + s + " value=" + map.get(s));}// 方法四 valuesSystem.out.println("values");for (String s : map.values()) {System.out.println("value =" + s);}//方法五 forEachSystem.out.println("forEach");map.forEach((key,value) ->{System.out.println(key+":"+value);});}

Map接口概述

Map是一个将键映射到值的对象。映射不能包含重复的键:每个键最多可以映射到一个值。它对数学函数抽象进行建模。该Map接口包括用于基本操作(例如put、get、remove、 containsKey、containsValue、size和empty)、批量操作(例如putAll和clear)和集合视图(例如keySet、entrySet和values)的方法。

Java 平台包含三个通用Map实现: HashMap、 TreeMap和 LinkedHashMap。它们的行为和性能与Set接口中所述的 HashSet、TreeSet和LinkedHashSet完全类似。

Map集合Lambda操作:

// 按部门分组员工Map<Department, List<Employee>> byDept = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment));// 按部门计算工资总和Map<Department, Integer> totalByDept = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment,Collectors.summingInt(Employee::getSalary)));// 将学生分为合格和不合格Map<Boolean, List<Student>> passFailing = students.stream().collect(Collectors.partitioningBy(s -> s.getGrade()>= PASS_THRESHOLD));// 按城市对 Person 对象进行分类Map<String, List<Person>> peopleByCity= personStream.collect(Collectors.groupingBy(Person::getCity));// 级联收集器Map<String, Map<String, List<Person>>> peopleByStateAndCity= personStream.collect(Collectors.groupingBy(Person::getState,Collectors.groupingBy(Person::getCity)))

亦余心之所善兮,虽九死其犹未悔。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。