-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConcordanceWithlambda.java
83 lines (66 loc) · 2.64 KB
/
ConcordanceWithlambda.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.AliIssa;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class ConcordanceWithlambda {
private static Map<String, Integer> HashMap = new HashMap<>();
public static void main(String [] args) {
String line;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence:");
line = scan.nextLine();
createMap(line); //create a map using the line provided
displayMap(); // display each word with its number of occurrence
scan.close();
}
private static void createMap(String line) {
line.replace("\\p{p}", ""); // this will remove all the punctuation from the sentence
String [] words = line.split("\\s+");// "\\s+" will use any number of spaces as a delimeter
// .split is a method of String class that decompose a line of text into words
for(String word: words) {
if(HashMap.containsKey(word)) { // verifies if a "key" exists in the linkedlist
int counter = HashMap.get(word); // gets the "Value" associated with the "Key"
HashMap.put(word, ++counter); //updates the value of the word counter by 1
// note that counter++ won't work
}
else {
HashMap.put(word,1);
}
}
}
private static void displayMap() {
Set<String> wordsSet = HashMap.keySet();// we create a set containing the "keys" of the map
// the reason we use a set because we don't want duplicate keys
// TreeSet<String> wordsSorted = new TreeSet<>(new Comparator<String>(){
// public int compare(String s1, String s2) {
// if(s1.length() != s2.length()) {
// return s1.length() - s2.length();
// }
// return s1.compareToIgnoreCase(s2);
// }
//
// });
TreeSet<String> wordsSorted = new TreeSet<>(
(s1,s2)->{ // in the lambda, we write here between () the parameter of the method in the functional interface
// here we provide the implementation of the method in the functional interface
if(s1.length() != s2.length()) {
return s1.length() - s2.length();
}
return s1.compareToIgnoreCase(s2);
});
for(String word: wordsSet) {
wordsSorted.add(word);
}
System.out.println("Using a TreeSet: ");
for(String word: wordsSorted) {
System.out.println(word +": "+ HashMap.get(word));
}// here the words will printed in a certain order, we can provide our own comparison standards
System.out.println("Using a Set:");
for(String word: wordsSet) {
System.out.println(word + ": "+ HashMap.get(word));
}// words will be printed depending of the sentence order
}
}