2016-08-23 4 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 행운"와 같은 문자열 입력을 가지고 단어 배열 안녕하세요, 행운이있다 . 3, 행운 : 3자바 8 스트림 및 다중 목록과 필터링

나는 이것이 위의 코드를 사용하려하지만, 어떤 이유로 그것을하지 않습니다, 제발 수있는 사람의 도움 안녕하세요, 6 :

나는이 숫자와 같은 문자열을 검색 할 ?

답변

1

groupingBy() 및 counting() 함수를 포함하는 것을 잊었습니다. 또한 SPACE 및 NUMBER가 누락되어 ""및 "숫자"를 나타내는 것으로 가정합니다.

누락 된 기능으로 인해 더 큰 수정을했습니다. - "지도"에 문자열 값과 발생 수를 수집하고 숫자 발생 수를 추가했습니다 (수동으로 "숫자"키를 "맵"에 추가 함)). 이 기능은 원하는대로 작동합니다.

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"발생을 추가하는 것이 좋은 해결책이라고 믿습니다.