I am trying to convert the python code provided by our instructor into the equivalent Java code. This portion of code is supposed to read from a txt file, parse the data with regex, and store them as an array of words. A restriction for this exercise is that the "data_storage_obj" is used to imitate JavaScript Object, and we have to keep them in that key-value format.
The instruction indicates that a data structure in Java that is closest to a JavaScript Object is "HashMap". However, because key each maps to a different data structure for storing the corresponding information, the best type I can think of so far is "Object". However, one of the keys maps to a lambda function, so I get this error message saying "error: incompatible types: Object is not a functional interface". I'm wondering what type I should be using to cover all the types I am going to store as the map values.
A snippet of code provided by the instructor:
def extract_words(obj, path_to_file):
with open(path_to_file) as f:
obj['data'] = f.read()
pattern = re.compile('[\W_]+')
data_str = ''.join(pattern.sub(' ', obj['data']).lower())
obj['data'] = data_str.split()
data_storage_obj = {
'data' : [],
'init' : lambda path_to_file : extract_words(data_storage_obj, path_to_file),
'words' : lambda : data_storage_obj['data']
}
data_storage_obj['init'](sys.argv[1])
Java code I have been working on:
public class Twelve{
static void extract_words(Object obj, String path_to_file){
System.out.println("extract_words()");
if(obj instanceof HashMap){
HashMap<String, Object> hashMap = (HashMap<String, Object>) obj;
String file_data = "";
try {
file_data = (new String(Files.readAllBytes(Paths.get(path_to_file)))).replaceAll("[\\W_]+", " ").toLowerCase();
} catch (IOException e) {
e.printStackTrace();
}
hashMap.put("data", Arrays.asList(file_data.split(" ")));
obj = hashMap;
}
}
static HashMap<String, Object> data_storage_obj = new HashMap<>();
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
data_storage_obj.put("data", data);
data_storage_obj.put("init", path_to_file -> extract_words(data_storage_obj, path_to_file));
data_storage_obj.put("words", data_storage_obj.get("data"));
}
}