java8 List,Map,对象等集合常用操作

//新建map
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
//传统map遍历
for (Map.Entry<String,Integer> map : items.entrySet()){
    System.out.println(map.getKey() +"--"+map.getValue() );
}
//java8 遍历map
items.forEach((k,v) -> System.out.println(k + "---" + v));
//新增判断
items.forEach((k,v)->{
    System.out.println(k+"---"+v);
    if("E".equals(k)){
        System.out.println("Hello E");
    }
});
//新增list
List<String> itemsList = new ArrayList<>();
itemsList.add("A");
itemsList.add("B");
itemsList.add("C");
itemsList.add("D");
itemsList.add("E");
//遍历list方式
itemsList.forEach(item -> System.out.println(item));
//新增判读
itemsList.forEach(item -> {
    if("D".equals(item)){
        System.out.println("Hello D");
    }
});
//filter 新增过滤条件
itemsList.stream()
.filter(s->s.contains("A"))
.forEach(System.out::println);
//遍历对象
List<Comments> commentsList = new ArrayList<>();
Comments comments = new Comments();
comments.setContent("123");
Comments comments1 = new Comments();
comments1.setContent("234");
commentsList.add(comments);
commentsList.add(comments1);
//遍历
commentsList.forEach(comments2 -> System.out.println(comments2.getContent()));
//新增filter过滤条件
commentsList.stream()
        .filter(s->s.getContent().contains("123"))
        .forEach(System.out::println);
//list 集合排序
List<String> names2 = new ArrayList<String>();
names2.add("Google ");
names2.add("Runoob ");
names2.add("Taobao ");
names2.add("Baidu ");
names2.add("Sina ");
//java7 排序方式
Collections.sort(names2, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
});
System.out.println(names2);
//java8 快捷
Collections.sort(names2,(s1,s2) -> s1.compareTo(s2));
System.out.println(names2);
//java8 Collectors常用操作
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("筛选列表: " + filtered);
//过滤合并
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);
//IntSummaryStatistics 统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

IntSummaryStatistics stats = numbers.stream().mapToInt((x) ->x).summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
    原文作者:星之火燎原
    原文地址: https://blog.csdn.net/baidu_34046383/article/details/83788018
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞