java8 summarizes the of recommendation by several ways to count the number of letters in a string

  • 2020-11-25 07:16:33
  • OfStack

1. Count the number of letters in the string (and keep them in alphabetical order)

aabbbbbbbba oh, bcab cdabc deaaa

There are 5 ways I know how to do it so far. Oh, if you have better ones, please tell me


// way 1
  public static void letterCount1(String s) {
  	s=s.replaceAll(" +", "");
	   //1, Convert to an array of characters 
	  char c[]=s.toCharArray();
	  
	  Map<Character, Integer> tree=new TreeMap<Character, Integer>();
	  for (int i = 0; i < c.length; i++) {
		// The first 1 Time: a,1
		// The first 2 Time: a,2 
	   //2, Gets the value corresponding to the key 
		Integer value=tree.get(c[i]);
//		    The compiler: Integer value = (Integer)tree.get(Character.valueOf(c[i]));
	   //3, Storage judgment 
		tree.put(c[i], value==null? 1:value+1);
	  }
	  
	  // If the result format is required: a(5)b(4)c(3)d(2)e(1)
	  StringBuilder sbu=new StringBuilder();
	  for(Character key:tree.keySet()){
		Integer count=tree.get(key);
		sbu.append(key).append("(").append(count).append(")");
	  }
	  // will sbu Convert to string 
	  System.out.println(sbu.toString());
	}
   
  // way 2  Use the stream 
  // This is testing special characters , Such as \  \n when , He's not in the right order , This is a Map Caused by the 
  // Solution use 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);
  	
  }
  
  // way 3  use Collections.frequency
  // It's just a string that becomes a set for each string , Compare each string loop to a collection 
  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);
  }
  
  // way 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);
  }
  
  
  // way 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);
  }
  
  
  
  // Use opportunely split
 	public static int stringCount(String maxstr, String substr) {
		//  Pay attention to 
		// 1. Such as qqqq, Could not find , Returns the string directly 
		// 2. Such as qqqjava, There are no other characters at the end , There's no splitting , So you can add 1 A blank space 
		// 3.java11 No characters at the beginning, no relationship, automatic empty fill 
		// 4. For special characters , Be careful with escape characters 
		int count = (maxstr + " ").split(substr).length - 1;
		// System.out.println("\"" + minstr + "\"" + " Occurrence times of string: " + count);
		return count;
	}

  // If case insensitive, then 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. Count the number of words in the string (English only)

This is actually the same thing as the 1 up here, but let me just write 1 neat way to do it


 public static void wordStringCount(String s) {
  	// So here we start with a string , The split becomes a stream of strings 
    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. Count the number of words in the text (English only)


 // statistical 1 The number of words in the text 
  public static void wordFileCount(String path) throws IOException{
  	// Here, 1 Start string stream 
  	// First division 
  	// In becoming a character stream 
  	// In the screen 
  	 Map<String, Long> result = Files.lines(Paths.get(path),Charset.defaultCharset())
  			         .parallel()
					 // String flow -- segmentation -- String flow 
					 .flatMap(str->Arrays.stream(str.split(" +"))) 
					 .map(word -> word.replaceAll("[^a-zA-Z]", ""))
					// Remove empty 
					 .filter(word->word.length()>0) 
				 .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
  	System.out.println(result);
  }

4. Other irrelevant items

We know that mutable argument list, you can pass no arguments

for


public void testName() {
      System.out.println("a");
   }

    public void testName(String ... s) {
        // Don't pass parameters ,s Will be initialized by default 1 An object 
     System.out.println("b");
  }

Now call testName() to print what ? , which prints a and automatically matches methods whose parameters are really empty


Related articles: