1. 程式人生 > >java8 統計字串字母個數的幾種方法(有你沒見到過的)

java8 統計字串字母個數的幾種方法(有你沒見到過的)

1.統計字串字母個數(並且保持字母順序)

比如: aabbbbbbbba喔喔bcab  cdabc  deaaa

目前我做知道的有5種方式,如果你還有更好的,歡迎賜教

要求:統計字串的字元個數,最好按順序輸出每個字元的個數

//方式1
    public static void letterCount1(String s) {
    	s=s.replaceAll(" +", "");
	     //1,轉換成字元陣列
	    char c[]=s.toCharArray();
	   
	    Map<Character, Integer> tree=new TreeMap<Character, Integer>();
	    for (int i = 0; i < c.length; i++) {
		//第一次:a,1
		//第二次:a,2  
	     //2,獲取鍵所對應的值
		Integer value=tree.get(c[i]);
	     //3,儲存判斷
		tree.put(c[i], value==null? 1:value+1);
	    }
	    System.out.println(tree);
	
	}
     
    //方式2  使用流
    //這個在測試特殊字元,比如\    \n時,他的順序會不對,這個是Map造成的
    //解決辦法使用TreeMap
    public static void letterCount2(String s) {
    	s=s.replaceAll(" +", "");
    	TreeMap<String, Long> result = Arrays.stream(s.split(""))
        		                .sorted()
//                              .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
                                .collect(Collectors.groupingBy(Function.identity(),TreeMap::new,Collectors.counting()));
        System.out.println(result);
    	
    }
    //或者
	public static void letterCount2_1(String s) throws Exception {
		s=s.replaceAll(" +", "");
		Stream<String> words = Arrays.stream(s.split(""));
		Map<String, Integer> wordsCount = words.collect(Collectors.toMap(k -> k, v -> 1,
		                                                      (i, j) -> i + j));
		System.out.println(wordsCount);
	}
    
    //方式3 使用Collections.frequency
    //其實就是字串變成集合存每個字串,把每個字串迴圈跟集合比較
    public static void letterCount3(String s) {
    	s=s.replaceAll(" +", "");
    	List<String> list=Arrays.asList(s.split(""));
    	Map<String,Integer> map=new TreeMap<String, Integer>();
    	for (String str : list) {
    		map.put(str, Collections.frequency(list, str));
		}
    	System.out.println(map);
    }
    
    //方式4
    public static void letterCount4(String s) {
    	s=s.replaceAll(" +", "");
    	String[] strs = s.split("");
    	Map<String,Integer> map=new TreeMap<String, Integer>();
    	for (String str : strs) {
    		map.put(str, stringCount(s, str));
		}
    	System.out.println(map);
    }
    
    
    //方式5
    public static void letterCount5(String s) {
    	s=s.replaceAll(" +", "");
    	String[] strs = s.split("");
    	Map<String,Integer> map=new TreeMap<String, Integer>();
    	for (String str : strs) {
    		map.put(str, stringCount2(s, str));
		}
    	System.out.println(map);
    }
    
    
    
    //巧用split
  	public static int stringCount(String maxstr, String substr) {
		// 注意
		// 1.比如qqqq,沒有找到,則直接返回這個字串
		// 2.比如qqqjava,末尾沒有其他字元,這時也不會分割,所以可以新增一個空格
		// 3.java11開頭沒有字元,沒有關係,自動空填充
		// 4.對於特殊字元,要注意使用轉義符
		int count = (maxstr + " ").split(substr).length - 1;
		// System.out.println("\"" + minstr + "\"" + "字串出現次數:" + count);
		return count;
	}

    //如果要不區分大小寫,則compile(minstr,CASE_INSENSITIVE)
	public static int stringCount2(String maxstr, String substr) {
		int count = 0;
		Matcher m = Pattern.compile(substr).matcher(maxstr);
		while (m.find()) {
			count++;
		}
        return count;
	}

2.統計字串的單詞個數

這個其實跟上面一樣的,下面只寫一個簡潔的方法

 public static void wordStringCount(String s) {
    	//這裡開始是字串,分割後變成字串流
        Map<String, Long> result = Arrays.stream(s.split("\\s+"))
        		                          .map(word -> word.replaceAll("[^a-zA-Z]", ""))
                                               .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
        System.out.println(result);
    	
    }

3.統計文字單詞個數

 //統計一個文字中單詞的個數
    public static void wordFileCount(String path) throws IOException{
    	//這裡一開始字串流
    	//先分割
    	//在變成字元流
    	//在篩選
    	 Map<String, Long> result = Files.lines(Paths.get(path),Charset.defaultCharset())
    			                 .parallel()
					  //字串流--分割--字串流
					 .flatMap(str->Arrays.stream(str.split(" +"))) 
					 .map(word -> word.replaceAll("[^a-zA-Z]", ""))
					//去掉空
					 .filter(word->word.length()>0) 
				 .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
    	System.out.println(result);
    }
 //優化:更精確的是根據非單詞來分組
    public static void wordFileCount0(String path) throws IOException{
    	Map<String, Long> result = Files.lines(Paths.get(path),Charset.defaultCharset())
    			.parallel()
    			//字串流--分割--字串流
    			.flatMap(str->Arrays.stream(str.split("[^a-zA-Z]+"))) 
    			//去掉\n
    			.filter(word->word.length()>0) 
    			.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
    	System.out.println(result);
    }