jdk1.8后对集合的遍历方法更新

一、首先对Map集合的遍历方法

jdk1.7之前的遍历方法如下:

for (Map.Entry<String, Integer> entry : ordermap.entrySet()) {
     System.out.println("key : " + entry.getKey() + " value : " + entry.getValue());
}

jdk1.8之后可以结合lambda表达式 

1、

// 循环,key,value
 map.forEach((k, v) -> { doSomething(k,v); });

2、

// 循环map中的values
map.values().forEach(System.out :: println);

3、

// Map.entrySet来遍历key,value, 大容量时推荐使用
map.entrySet().forEach(entry -> {
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
});

4、

// 使用iterator来遍历Map.entrySet
map.entrySet().iterator().forEachRemaining(iter -> {
    System.out.println(iter.getKey());
    System.out.println(iter.getValue());
});

5、

// 遍历key
map.keySet().forEach(key -> {
    System.out.println(key);
    System.out.println(map.get(key));
});

二、对list的遍历,在jdk1.8也做了简化,也是配合lambda表达式

list.forEach(str -> {
            if ("C".equals(str)) {
                str = "我是C";
            }
            System.out.println(str);
});

三、对list的分组操作

java8之前List分组

假设有个student类,有id、name、score属性,list集合中存放所有学生信息,现在要根据学生姓名进行分组。

public Map<String, List<Student>> groupList(List<Student> students) {
    Map<String, List<Student>> map = new Hash<>();
    for (Student student : students) {
        List<Student> tmpList = map.get(student.getName());
        if (tmpList == null) {
            tmpList = new ArrayList<>();
            tmpList.add(student);
            map.put(student.getName(), tmpList);
        } else {
            tmpList.add(student);
        }
    }
    return map;
}

java8的List分组

public Map<String, List<Student>> groupList(List<Student> students) {
    Map<String, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName));
    return map;
}

对list中对象某个属性去重(比较常用)

List<Student> persons = Arrays.asList(p1, p2, p3);
		List<Student> unique = persons.stream().collect(Collectors.collectingAndThen(
				Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
		unique.forEach(p -> System.out.println(p));

对list中对象多个属性去重(比较常用)

List<Student> persons = Arrays.asList(p1, p2, p3);
		List<Student> unique = persons.stream().collect(Collectors.collectingAndThen(
				Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getName()+";"+s.getAge()))), ArrayList::new));
		unique.forEach(p -> System.out.println(p));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章