编程语言
首页 > 编程语言> > java 查找list中指定字符串出现的次数

java 查找list中指定字符串出现的次数

作者:互联网

package com.gblfy.ws.client;

import java.util.ArrayList;
import java.util.List;

public class StrCount {

    public static void main(String[] args) {

        //指定字符串
        String keywords = "2021-08-22";
        //构造集合数据
        List<String> dataList = dataList();

        //字符串出现的次数
        int appearNum = findStrCount(dataList, keywords);
        System.out.println("keywords在集合中出现的次数为:" + appearNum);
    }

    /**
     * 根据指定字符串,查询出现的次数
     *
     * @param keyList
     * @param keywords
     * @return
     */
    public static int findStrCount(List<String> keyList, String keywords) {
        int count = 0;
        for (String keyVal : keyList) {
            String keyValdeal = keyVal.substring(0, 10);
            if (keyValdeal.equals(keywords)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 构造list数据
     *
     * @return
     */
    public static List<String> dataList() {
        List<String> keyStrList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            keyStrList.add("2021-08-0" + String.valueOf(i));
        }
        return keyStrList;
    }
}

标签:java,String,int,List,list,查找,keywords,return,public
来源: https://blog.csdn.net/weixin_40816738/article/details/120420738