12
12
public class AnagramsTogetherLexicographically {
13
13
14
14
/**
15
- * Takes an array of String {@param s } and prints anagrams in groups where the groups
15
+ * Takes an array of String {@code strings } and prints anagrams in groups where the groups
16
16
* are arranged lexicographically and the strings within each group are also arranged
17
17
* lexicographically.
18
18
*
19
- * @param s
19
+ * @param strings
20
20
*/
21
- public static void printAnagramsTogether (String [] s ) {
21
+ public static void printAnagramsTogether (String [] strings ) {
22
22
23
23
HashMap <String , List <Integer >> hashMap = new HashMap <>();
24
- TreeSet <List <String >> treeSet = new TreeSet <>(new Comparator () {
25
- @ Override
26
- public int compare (Object o1 , Object o2 ) {
27
- if (o1 instanceof List <?> && o2 instanceof List <?>) {
28
- return ((List <String >) o1 ).get (0 ).compareTo (((List <String >) o2 ).get (0 ));
29
- } else {
30
- return 0 ;
31
- }
24
+ TreeSet <List <String >> treeSet = new TreeSet <>((Comparator ) (o1 , o2 ) -> {
25
+ if (o1 instanceof List <?> && o2 instanceof List <?>) {
26
+ return ((List <String >) o1 ).get (0 ).compareTo (((List <String >) o2 ).get (0 ));
27
+ } else {
28
+ return 0 ;
32
29
}
33
30
});
34
31
35
- for (int i = 0 ; i < s .length ; i ++) {
36
- String removeSpaces = s [i ].replaceAll ("\\ s+" , "" );
32
+ for (int i = 0 ; i < strings .length ; i ++) {
33
+ String removeSpaces = strings [i ].replaceAll ("\\ s+" , "" );
37
34
char [] chars = removeSpaces .toCharArray ();
38
35
Arrays .sort (chars );
39
36
@@ -50,17 +47,14 @@ public int compare(Object o1, Object o2) {
50
47
List <String > anagrams = new ArrayList <>();
51
48
52
49
for (int i = 0 ; i < entry .getValue ().size (); i ++) {
53
- anagrams .add (s [entry .getValue ().get (i )]);
50
+ anagrams .add (strings [entry .getValue ().get (i )]);
54
51
}
55
52
56
53
Collections .sort (anagrams ); // arrange anagrams lexicographically within a single line
57
54
treeSet .add (anagrams ); // sort the entire output lexicographically
58
55
}
59
56
60
- Iterator iterator = treeSet .iterator ();
61
- while (iterator .hasNext ()) {
62
- System .out .println (iterator .next ());
63
- }
57
+ treeSet .stream ().flatMap (Collection ::stream ).forEach (System .out ::println );
64
58
}
65
59
66
60
/**
@@ -72,6 +66,7 @@ public static void main(String[] args) {
72
66
Scanner in = new Scanner (System .in );
73
67
List <String > strings = new ArrayList <>();
74
68
String s ;
69
+ System .out .println ("Input string in separate lines (blank string to stop):" );
75
70
// you should use in.hasNextLine()
76
71
while (!(s = in .nextLine ()).trim ().equals ("" )) {
77
72
strings .add (s );
0 commit comments