How to find your favorite girlfriend with java8 stream API

The traditional Java collection operation is a little verbose. When we need to filter and sort the combined elements, we usually need to write several lines of code and define temporary variables. The java8 stream API can greatly simplify this operation, with fewer lines of code and easy to read.

Let's take "looking for a girlfriend" as an example to see how fragrant the stream API of Java 8 is compared with the traditional writing method. Suppose we define a girlfriend class with several key indicators: name, height, weight and face value. As follows:

class Girl {
    private String name;
    private int height;
    private int weight;
    private int score;
    // 省略get,set及hashCode等方法
}    

We have a list of young women of school age as follows:

public static List<Girl> initGirlList(){
    List<Girl> result = new ArrayList<>();
    result.add(new Girl("赵小花",170,60,6));
    result.add(new Girl("钱小花",171,62,7));
    result.add(new Girl("孙小花",172,59,8));
    // 省略.... 
    return result;
}

Screening criteria for favorite girlfriends

Suppose your favorite girlfriend is: weight, moderate height, and the higher the appearance value, the better. The condition of this setting is to find out the girls with height > = 162 and weight < = 53, and then sort the top three by their appearance value.

Java 7 writing

Data De duplication

Since the data may be duplicated, which will interfere with our screening, the first step is to remove the duplicate data. The code is as follows:

List<Girl> girlList = initGirlList();// 初始化一批数据
// 数据去重
List<Girl> distinctGirl = new ArrayList<>();
for (Girl g: girlList){
    if(!distinctGirl.contains(g)){
        distinctGirl.add(g);
    }
}

Here is a new distinguishgirl to store the data after de duplication. The code is very simple and there is nothing to say.

Filter data

Below, we want to remove the unqualified data. The screening conditions are height > = 162 and weight < = 53. The code is as follows:

// 过滤身高,体重不符合的
List<Girl> girlTemp = new ArrayList<>();
for(Girl g: distinctGirl){
    if(g.getHeight() >= 162 && g.getWeight() <= 53){
        girlTemp.add(g);
    }
}

Here, use the distinguishgirl after de duplication in the previous step to traverse, and put the qualified into the new list girltemp. Here, an intermediate list is created.

Data sorting

After the above two lengthy steps, we have obtained the data that meets our requirements. Now we need to rank according to the appearance value. The code is as follows:

Collections.sort(girlTemp,new Comparator<Girl>() {
    @Override
    public int compare(Girl g1,Girl g2) {
        BigDecimal score1 = new BigDecimal(g1.getscore());
        BigDecimal score2 = new BigDecimal(g2.getscore());
        return score2.subtract(score1).intValue();
    }
});

Here, the sort method of the collections tool class is used, an anonymous class is passed, and the sorting logic is implemented in its compare method, which is still the operation of traditional collection sorting.

Output results

After the above steps of traditional Java collection operation, we finally get the desired data. Now we're going to output the top three.

int i = 1;
for (Girl g : girlTemp) {
    if(i>=3){
        break;
    }
    System.out.println(g.toString());
}

OK, so far, our program outputs the screening results. The above writing seems to be logical and gradual step by step. Yes, this traditional way of writing has been happily written by Java programmers for many years. At first glance, there are more than 20 lines of this code! But the implementation logic is not too complicated? After a while, if you look back at the code, you probably forget what such a large piece of code is for. If comments are OK, a glance can help you quickly figure out what the code has done. If there are no comments, you need to read more than 20 lines of code line by line to understand its logic.

How to write java8 stream API

Here we are reviewing our goal: find out the girls with height > = 162 and weight < = 53 from a girllist, and then sort the top three by their appearance value. The code of java8 is as follows:

List<Girl> girlList = initGirlList();
girlList.stream()
        .filter( g -> g.getHeight() >= 162 && g.getWeight() <= 53)
        .distinct()
        .sorted(Comparator.comparing(Girl::getscore).reversed())
        .limit(3)
        .forEach( g -> System.out.println(g.toString()));

Code 6 lines! And even if you don't know the stream API, and you look at the code for the first time, you can guess what it means. Filter filter, distinct de duplication, sort sort, limit, limit, foreach traversal, that's all.

epilogue

Java is such an old language that it is now Java 13. However, I think the most influential version is java 8. When I was at school, the school used the writing method of Java 6. After working, I began to write the try with resource and diamond syntax of Java 7. Until now, many projects on the market are Java 7. Once a colleague told me that he wrote Java 8 in the former company and was told by the project manager. I asked why. He said that because the project manager thought that writing Java 7 was easy to maintain, everyone in the team would write java 7, and not many people wrote Java 8... Speechless.

If you haven't used java 8 yet, I hope the small examples in this article have successfully aroused your interest in using java 8. Questionnaire: what version do you use now? The complete source code is attached below the comments

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>