Javaでのstream操作の使用を簡単に学習

8093 ワード

streamは、コレクションを処理する新しい方法の1つであり、デリバリー(distinct()、ソート(sort()、フィルタ(filter()、パケット(group()、統計(sum();count()、および抽出(map)を含むことがよく用いられる.
エンティティクラスのテスト
import lombok.Data;
import java.util.Objects;

@Data
public class StreamTestStudent {
    /**
     *   
     */
    private Integer id;
    /**
     *   
     */
    private String name;
    /**
     *   
     */
    private Double score;
    /**
     *   
     */
    private String gradeName;
    /**
     *   
     */
    private String className;

    public StreamTestStudent(Integer id, String name, Double score, String gradeName, String className) {
        this.id = id;
        this.name = name;
        this.score = score;
        this.gradeName = gradeName;
        this.className = className;
    }

    public StreamTestStudent() {
    }

    /**
     *   equals hashCode  
     *   id         
     * @param o
     * @return
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StreamTestStudent that = (StreamTestStudent) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}


テストの使用
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class App {
    List studentList = new ArrayList<>();

    {
        //        
        studentList.add(new StreamTestStudent(1, "oneone", 56.1, "   ", "  "));
        studentList.add(new StreamTestStudent(2, "twotwo", 34.6, "   ", "  "));
        studentList.add(new StreamTestStudent(3, "threethree", 93.2, "   ", "  "));
        studentList.add(new StreamTestStudent(4, "fourfour", 80.0, "   ", "  "));
        studentList.add(new StreamTestStudent(5, "FiveFive", 45.4, "   ", "  "));
        studentList.add(new StreamTestStudent(6, "sixsix", 77.3, "   ", "  "));
        studentList.add(new StreamTestStudent(7, "sevenseven", 84.3, "   ", "  "));
        studentList.add(new StreamTestStudent(8, "eighteight", 91.2, "   ", "  "));
        studentList.add(new StreamTestStudent(9, "ninenine", 44.4, "   ", "  "));
        studentList.add(new StreamTestStudent(10, "tenten", 69.0, "   ", "  "));
        //    ,   equals  ,  id       
        studentList.add(new StreamTestStudent(1, "tenten", 42.3, "   ", "  "));
        //studentList.add(new StreamTestStudent(2, "tenten22", 59.0, "   ", "  "));
        //studentList.add(new StreamTestStudent(3, "tenten33", 59.0, "   ", "  "));
    }

    /**
     *        
     */
    @Test
    public void test01() {
        studentList.forEach(temp -> System.out.println(temp));
    }

    /**
     *   
     */
    @Test
    public void test02() {
        List distinctList = studentList.stream().distinct().collect(Collectors.toList());
        System.out.println("    ======" + studentList.size());
        System.out.println("      ======" + distinctList.size());
        distinctList.forEach(t -> System.out.println(t));
    }

    /**
     *   
     * (a, b) -> a.getId() - b.getId()        
     * (a, b) -> b.getId() - a.getId()                
     * a,b        
     */
    @Test
    public void test03() {
        List sortList = studentList.stream().sorted((a, b) -> b.getId() - a.getId()).collect(Collectors.toList());
        sortList.forEach(t -> System.out.println(t));
    }

    /**
     *   
     *                 (     60   )
     */
    @Test
    public void test04() {
        List filterList = studentList.stream().filter(temp -> temp.getScore() > 60).collect(Collectors.toList());
        System.out.println("     ===" + filterList.size());
        filterList.forEach(t -> System.out.println(t));
    }

    /**
     *   
     *               (           )
     */
    @Test
    public void test05() {
        List nameList = studentList.stream().map(temp -> temp.getName()).collect(Collectors.toList());
        nameList.forEach(t -> System.out.println(t));
    }

    /**
     *      map,map key   ,value     
     */
    @Test
    public void test06() {
        //StreamTestStudent::getName        name  ,
        // (a, b) -> b        key ,  b           ;;;
        //   (a, b) -> a         ;;; [             ,        ]a
        //            key      
        Map toStudentMap = studentList.stream().collect(Collectors.toMap(StreamTestStudent::getName, temp -> temp, (a, b) -> a));
        toStudentMap.entrySet().forEach(e -> System.out.println(e.getKey() + "==" + e.getValue()));
    }

    /**
     *   
     *              
     */
    @Test
    public void test07() {
        //  
        double sum = studentList.stream().mapToDouble(temp -> temp.getScore()).sum();
        int sum1 = studentList.stream().mapToInt(temp -> temp.getId()).sum();
        System.out.println(sum1);
        System.out.println(sum);

        //  60     
        double sum2 = studentList.stream().filter(temp -> temp.getScore() > 60).mapToDouble(temp -> temp.getScore()).sum();
        System.out.println(sum2);
    }

    /**
     *   
     *         list   list.         
     */
    @Test
    public void test08() {
        Map> gradeNameGroup = studentList.stream().collect(Collectors.groupingBy(temp -> temp.getGradeName()));
        gradeNameGroup.entrySet().forEach(e -> {
            e.getValue().forEach(t -> System.out.println(e.getKey() + "==" + t.toString()));
        });
    }

    /**
     *     
     *         list   list.         ,         
     */
    @Test
    public void test09() {
        Map>> groupByGradeNextClass = studentList.stream().collect(Collectors.groupingBy(temp -> temp.getGradeName(), Collectors.groupingBy(temp -> temp.getClassName())));
        groupByGradeNextClass.entrySet().forEach(e -> {
            Map> value = e.getValue();
            value.entrySet().forEach(m -> {
                m.getValue().forEach(t -> System.out.println(e.getKey() + "==" + m.getKey() + "==" + t.toString()));
            });
        });
    }

    /**
     *               
     *         list   list.         ,         ,        
     */
    @Test
    public void test10() {
        Map> groupAndSum = studentList.stream().collect(Collectors.groupingBy(temp -> temp.getGradeName(), Collectors.groupingBy(temp -> temp.getClassName(), Collectors.summingDouble(temp -> temp.getScore()))));
        groupAndSum.entrySet().forEach(e -> {
            e.getValue().entrySet().forEach(t -> {
                System.out.println(e.getKey() + "==" + t.getKey() + "==" + t.getValue());
            });
        });

    }

    /**
     *               
     *         list   list.         ,         ,           (>60)   
     */
    @Test
    public void test11() {
        Map> groupCount = studentList.stream().filter(temp -> temp.getScore() > 60).collect(Collectors.groupingBy(StreamTestStudent::getGradeName, Collectors.groupingBy(StreamTestStudent::getClassName, Collectors.counting())));
        groupCount.entrySet().forEach(e -> {
            e.getValue().entrySet().forEach(t -> System.out.println(e.getKey() + "==" + t.getKey() + "==" + t.getValue()));
        });
    }

}