2016-08-23 28 views
1
public String count(String input, String... words) { 
    List<String> wordList = Arrays.asList(words); 
    Map<String, Long> maps = Arrays.asList(input.split(SPACE)).stream() 
      .collect(groupingBy(Function.identity(), counting())); 
    long number = 0; 
    StringJoiner stringJoiner = new StringJoiner(System.lineSeparator()); 
    String s = maps.entrySet().stream() 
      .map(entry -> wordList.contains(entry.getKey()) ? entry.getKey() + ":" + entry.getValue() : ""+number + entry.getValue()).collect(Collectors.joining(System.lineSeparator())); 
    stringJoiner.add(s); 
    stringJoiner.add(NUMBER + number); 
    return stringJoiner.toString(); 
} 

正如可以從上面的代碼見我有這樣「1個2喂運氣5喂7運氣你好10 11運氣」字符串輸入和詞陣列具有你好,運氣。爪哇8流和與多個列表過濾

我想搜索的字符串這樣的數字:6,你好:3,運氣:3

我想這個使用上面的代碼,但它不會因爲某種原因做,可以請別人幫忙?

回答

1

您忘記了包含groupingBy()和counting()函數。空格和數字也不見了,所以我認爲它們代表「」和「數字」。

我做了一個更大的修改,因爲缺少函數 - >我收集了字符串值和它們在「地圖」中出現的次數,並且還添加了數字的出現次數(手動添加「數字」鍵到「地圖」 )。該功能可以按照您的要求工作。

public String count(String input, String... words) 
{ 
    List<String> wordList = Arrays.asList(words); 
    Map<String, Long> maps = new HashMap<>(); 
    // count the number of occurences of each word and all the numbers in the "Input" argument, and save word as 
    // key, number as value 
    Arrays.asList(input.split(" ")).stream() 
      .forEach(str -> { 
       if (maps.containsKey(str)) 
       { 
        // it's a string already contained in map 
        Long l = maps.get(str); 
        maps.put(str, ++l); 
       } 
       else 
       { 
        try 
        { 
         Long parse = Long.parseLong(str); 
         // it's a number 
         if (maps.containsKey("numbers")) 
         { 
          Long l = maps.get("numbers"); 
          maps.put("numbers", ++l); 
         } 
         else 
         { 
          // first number added 
          maps.put("numbers", (long) 1); 
         } 
        } 
        catch (NumberFormatException e) 
        { 
         // it's a string, not yet added to map 
         maps.put(str, (long) 1); 
        } 
       } 
      }); 
    StringJoiner stringJoiner = new StringJoiner(System.lineSeparator()); 
    String s = maps.entrySet().stream() 
      // first we filter out words 
      .filter(entry -> wordList.contains(entry.getKey())) 
      // then we convert filtered words and value to string 
      .map(entry -> entry.getKey() + ":" + entry.getValue()) 
      // collect 
      .collect(Collectors.joining(System.lineSeparator())); 
    stringJoiner.add(s); 
    // add numbers at the end 
    stringJoiner.add("numbers:" + maps.get("numbers")); 
    return stringJoiner.toString(); 
} 

編輯:我意識到缺少的方法來自收集器類(Collectors.groupingBy和Collectors.counting)。我試圖用新信息修復你的代碼,但是除了我上面寫的函數之外,我看不到一個很好的解決方案。

問題在於計算給定輸入中的數字數量。您不能在流的.map或.filter函數內增加變量「long number」,因爲變量必須是最終的或有效的最終值。此外,無論如何,你需要做一個try catch塊。因此,我相信我的解決方案將所有內容與發生次數一起排序到Map中,然後過濾該映射以搜索搜索詞(「words」參數),最後手動添加「numbers」發生是一個很好的解決方案。