获取list中某个属性组成新的集合

获取list中某个属性组成新的集合

  • 按以往常用的方式
    Person p1 = new Person();
    p1.setName("张三");
    p1.setAge(20);
    Person p2 = new Person();
    p2.setName("李四");
    p2.setAge(18);
    
    List<Person> personList = new ArrayList<>(2);
    personList.add(p1);
    personList.add(p2);
    
    List<String> names = new ArrayList<>(personList.size());
    for (Person person : personList) {
        names.add(person.getName());
    }
    System.out.println(names);
    

    以上这种方式动不动就搞个循环,数据量大点就会出大事,轻的造成卡顿,严重的就Game Over了 ,好在Java8 List Stream解决了这个问题

  • Java8 list stream方式
    List<String> names = personList.stream().map(Person::getName).collect(toList());
    System.out.println(names);
    

    这种方式是不是简单到爆炸,这些只是stream应用的一部分,下面为大家提供一些应用demo

  • Java8 list stream demo
    List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
    System.out.println("列表: " +strings);
    
    long count = strings.stream().filter(String::isEmpty).count();
    System.out.println("空字符串数量为: " + count);
    
    count = strings.stream().filter(string -> string.length() == 3).count();
    System.out.println("字符串长度为 3 的数量为: " + count);
    
    List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(toList());
    System.out.println("筛选后的列表: " + filtered);
    
    String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
    System.out.println("合并字符串: " + mergedString);
    
    List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
    List<Integer> squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());
    System.out.println("Squares List: " + squaresList);
    System.out.println("列表: " +integers);
    
    IntSummaryStatistics stats = integers.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());
    System.out.println("随机数: ");
    
    Random random = new Random();
    random.ints().limit(10).sorted().forEach(System.out::println);
    
    // 并行处理
    count = strings.parallelStream().filter(String::isEmpty).count();
    System.out.println("空字符串的数量为: " + count);
    

你可能感兴趣的:(入门,java)