2016-08-23 24 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”发生是一个很好的解决方案。