File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Arrays ;
2+
3+ import static java .util .stream .Collectors .groupingBy ;
4+ import static java .util .stream .Collectors .joining ;
5+
6+ public class WordFrequency {
7+ public static String handle (String text ) {
8+ if (!text .equals ("" )) {
9+ return Arrays .stream (text .split (" " )).collect (groupingBy ((w ) -> w )).entrySet ().stream ()
10+ .sorted ((e1 , e2 ) -> e2 .getValue ().size () - e1 .getValue ().size ()).map ((e ) -> e .getKey () + " " + e .getValue ().size ()).collect (joining ("\r \n " ));
11+ }
12+ return "" ;
13+ }
14+ }
Original file line number Diff line number Diff line change 1+ import org .junit .Test ;
2+
3+ import static org .fest .assertions .api .Assertions .assertThat ;
4+
15public class WordFrequencyTest {
6+ @ Test
7+ public void should_handle_blank_text () {
8+ // given
9+ String text = "" ;
10+
11+ // when
12+ String result = WordFrequency .handle (text );
13+
14+ // then
15+ assertThat (result ).isEqualTo ("" );
16+ }
17+
18+ @ Test
19+ public void should_handle_one_word_text () {
20+ // given
21+ String text = "one" ;
22+
23+ // when
24+ String result = WordFrequency .handle (text );
25+
26+ // then
27+ assertThat (result ).isEqualTo ("one 1" );
28+ }
29+
30+ @ Test
31+ public void should_handle_two_different_words_text () {
32+ // given
33+ String text = "one two" ;
34+
35+ // when
36+ String result = WordFrequency .handle (text );
37+
38+ // then
39+ assertThat (result ).isEqualTo ("one 1\r \n two 1" );
40+ }
41+
42+ @ Test
43+ public void should_handle_duplicated_words_text () {
44+ // given
45+ String text = "one two one" ;
46+
47+ // when
48+ String result = WordFrequency .handle (text );
49+
50+ // then
51+ assertThat (result ).isEqualTo ("one 2\r \n two 1" );
52+ }
53+
54+ @ Test
55+ public void should_handle_the_order () {
56+ // given
57+ String text = "one two two" ;
58+
59+ // when
60+ String result = WordFrequency .handle (text );
61+
62+ // then
63+ assertThat (result ).isEqualTo ("two 2\r \n one 1" );
64+ }
265}
You can’t perform that action at this time.
0 commit comments