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));

 

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