I have wrote Java code to count sum of occurrences. It uses 2 .txt files as input and gives words and frequencies as output.
I would also like to print, which file how many times contains a given word. Do you have any idea how to do this?
public class JavaApplication2
{
public static void main(String[] args) throws IOException
{
Path filePath1 = Paths.get("test.txt");
Path filePath2 = Paths.get("test2.txt");
Scanner readerL = new Scanner(filePath1);
Scanner readerR = new Scanner(filePath2);
String line1 = readerL.nextLine();
String line2 = readerR.nextLine();
String text = new String();
text=text.concat(line1).concat(line2);
String[] keys = text.split("[!.?:;\\s]");
String[] uniqueKeys;
int count = 0;
System.out.println(text);
uniqueKeys = getUniqueKeys(keys);
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
System.out.println("["+key+"] frequency : "+count);
count=0;
}
}
private static String[] getUniqueKeys(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
Firstly, instead of using an array for unique keys, use a HashMap<String, Integer>. It's a lot more efficient.
Your best option is to run your processing over each line/file separately, and store these counts separately. Then merge the two counts to get the overall frequencies.
More Detail:
String[] keys = text.split("[!.?:;\\s]");
HashMap<String,Integer> uniqueKeys = new HashMap<>();
for(String key : keys){
if(uniqueKeys.containsKey(key)){
// if your keys is already in map, increment count of it
uniqueKeys.put(key, uniqueKeys.get(map) + 1);
}else{
// if it isn't in it, add it
uniqueKeys.put(key, 1);
}
}
// You now have the count of all unique keys in a given text
// To print them to console
for(Entry<String, Integer> keyCount : uniqueKeys.getEntrySet()){
System.out.println(keyCount.getKey() + ": " + keyCount.getValue());
}
// To merge, if you're using Java 8
for(Entry<String, Integer> keyEntry : uniqueKeys1.getEntrySet()){
uniqueKeys2.merge(keyEntry.getKey(), keyEntry.getValue(), Integer::add);
}
// To merge, otherwise
for(Entry<String, Integer> keyEntry : uniqueKeys1.getEntrySet()){
if(uniqueKeys2.containsKey()){
uniqueKeys2.put(keyEntry.getKey(),
uniqueKeys2.get(keyEntry.getKey()) + keyEntry.getValue());
}else{
uniqueKeys2.put(keyEntry.getKey(), keyEntry.getValue());
}
}
UPDATE : code for word(s) occurences (thanks #George)
This example is for a file, you can use it for multiple files :
public class MyTest {
Map<String,Integer> mapTable;
public MyTest(List<String> wordList){
//initialize map
makeMap(wordList);
}
public void makeMap(List<String> wordList){
mapTable = new HashMap();
for(int i = 0; i < wordList.size(); i++){
//fill the map up
mapTable.put(wordList.get(i), 0);
}
}
//update occurences in a map
public void updateMap(String [] _words){
for(int i = 0; i < _words.length; i++){
updateWordCount(_words[i]);
}
}
public void updateWordCount(String _word){
int value = 0;
//check if a word present
if(mapTable.containsKey(_word)){
value = mapTable.get(_word);
value++;
mapTable.put(_word, value);
}
}
public void DisplayCounts(){
for( String key : mapTable.keySet()){
System.out.println("Word : "+key+"\t Occurrence(s) :"+mapTable.get(key));
}
}
public void getWordCount(){
String filePath = "C:\\Users\\Jyo\\Desktop\\help.txt";
String line = "";
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(filePath);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
String _words[] = null;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
_words = line.split(" ");
updateMap(_words);
}
// Always close files.
bufferedReader.close();
} catch (Exception e) {
System.out.println("Error :"+e.getMessage());
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
List<String> wordList = new ArrayList<>();
wordList.add("data");
wordList.add("select");
MyTest mt = new MyTest(wordList);
mt.getWordCount();
mt.DisplayCounts();
}
}
import java.io.;
import java.util.;
public class file1{
public static void main(String[] args) throws Exception{
HashMap<String,Integer> words_fre = new HashMap<String,Integer>();
HashSet<String> words = new HashSet<String>();
try{
File folder = new File("/home/jsrathore/Dropbox/Semester 6th/IR_Lab/lab_01/one");
File[] listOfFiles = folder.listFiles();
BufferedReader bufferedReader=null;
FileInputStream inputfilename=null;
BufferedWriter out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename.txt",false), "UTF-8"));
for(File file : listOfFiles){
inputfilename= new FileInputStream(file);
/*System.out.println(file); */
bufferedReader= new BufferedReader(new InputStreamReader(inputfilename, "UTF-8"));
String s;
while((s = bufferedReader.readLine()) != null){
/*System.out.println(line);*/
s = s.replaceAll("\\<.*?>"," ");
if(s.contains("॥") || s.contains(":")|| s.contains("।")||
s.contains(",")|| s.contains("!")|| s.contains("?")){
s=s.replace("॥"," ");
s=s.replace(":"," ");
s=s.replace("।"," ");
s=s.replace(","," ");
s=s.replace("!"," ");
s=s.replace("?"," ");
}
StringTokenizer st = new StringTokenizer(s," ");
while (st.hasMoreTokens()) {
/*out.write(st.nextToken()+"\n");*/
String str=(st.nextToken()).toString();
words.add(str);
}
for(String str : words){
if(words_fre.containsKey(str)){
int a = words_fre.get(str);
words_fre.put(str,a+1);
}else{
words_fre.put(str,1);/*uwords++;//unique words count */
}
}
words.clear();
/*out.write("\n");
out.close();*/
}
Object[] key = words_fre.keySet().toArray();
Arrays.sort(key);
for (int i = 0; i < key.length; i++) {
//System.out.println(key[i]+"= "+words_fre.get(key[i]));
out.write(key[i]+" : "+words_fre.get(key[i]) +"\n");
}
}
out.close();
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Error in reading line");
}catch(IOException ex){
/*System.out.println("Error in reading line"+fileReader );*/
ex.printStackTrace();
}
}
}
Late answer, however below code will count word frequency efficiently if there are multiple files
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
public class WordCounter implements Runnable {
private final Scanner scanner;
private Map<String, AtomicLong> sharedCounter;
public WordCounter(Scanner scanner, Map<String, AtomicLong> sharedCounter) {
this.scanner = scanner;
this.sharedCounter = sharedCounter;
}
public void run() {
if (scanner == null) {
return;
}
while (scanner.hasNext()) {
String word = scanner.next().toLowerCase();
sharedCounter.putIfAbsent(word, new AtomicLong(0));
sharedCounter.get(word).incrementAndGet();
}
}
public static void main(String[] args) throws IOException {
// Number of parallel thread to run
int THREAD_COUNT = 10;
List<Path> paths = new ArrayList<>();
// Add path
paths.add(Paths.get("test1.txt"));
paths.add(Paths.get("test2.txt"));
// Shared word counter
Map<String, AtomicLong> sharedCounter = new ConcurrentHashMap<>();
ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
for (Path path : paths) {
executor.execute(new WordCounter(new Scanner(path), sharedCounter));
}
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.println(sharedCounter);
}
}
Related
i made an algorithm to do a calculus. it works well but bufferedWriter creates an empty file. I tried every kind of solutions, but every time it creates an empty file. i need the file as txt. how to fix it?
to help you reading my code:
addressCalc() is a function that open a txt and upload in an hashmap the data
uniqueAddress() is a function that calculate how many unique address there are in my data
nftNumbers() is a function that calculate how many nfts has each address
calculus() is the function that i need to print in a txt the final result
package calculator.v2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AlgorithmV2 {
HashMap <Integer, String> listAddress;
HashMap <Integer, String> totalAddress;
HashMap <String, String> uniqueAddress;
HashMap <Integer, String> orderAddress;
HashMap <String, Float> nfts;
int totalNfts = 33;
float cifra;
String lucifer, astaroth, beelzebup;
public AlgorithmV2() {
super();
listAddress = new HashMap<Integer, String>();
totalAddress = new HashMap<Integer, String>();
uniqueAddress = new HashMap<String, String>();
orderAddress = new HashMap<Integer, String>();
nfts = new HashMap<String, Float>();
addressCalc();
uniqueAddress();
nftNumbers();
calculus();
}
public float getCifra() {
return cifra;
}
public void setCifra(float cifra) {
this.cifra = cifra;
}
public HashMap<Integer, String> getTotalAddress() {
return totalAddress;
}
public void setTotalAddress(HashMap<Integer, String> totalAddress) {
this.totalAddress = totalAddress;
}
public HashMap<String, String> getUniqueAddress() {
return uniqueAddress;
}
public void setUniqueAddress(HashMap<String, String> uniqueAddress) {
this.uniqueAddress = uniqueAddress;
}
public HashMap<Integer, String> getOrderAddress() {
return orderAddress;
}
public void setOrderAddress(HashMap<Integer, String> orderAddress) {
this.orderAddress = orderAddress;
}
public HashMap<String, Float> getNfts() {
return nfts;
}
public void setNfts(HashMap<String, Float> nfts) {
this.nfts = nfts;
}
public int getTotalNfts() {
return totalNfts;
}
public void setTotalNfts(int totalNfts) {
this.totalNfts = totalNfts;
}
public float addressCalc() {
try {
FileReader reader = new FileReader("src\\calculator\\data\\snapshot.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
Pattern addressPattern = Pattern.compile("stars+[A-Za-z0-9]+");
int i = 0;
while ((line = bufferedReader.readLine()) != null) {
Matcher address = addressPattern.matcher(line);
if(address.find()) {
listAddress.put(i, address.group(0));
i++;
}
}
reader.close();
return 1;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
public void uniqueAddress(){
int temp = 0;
for(int i = 0; i < listAddress.size(); i++) {
if(uniqueAddress.get(listAddress.get(i)) == null) {
uniqueAddress.put(listAddress.get(i), listAddress.get(i));
orderAddress.put(temp, listAddress.get(i));
temp++;
}
}
}
public void nftNumbers() {
try {
FileReader reader = new FileReader("src\\calculator\\data\\data.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
cifra = Float.parseFloat(bufferedReader.readLine());
lucifer = bufferedReader.readLine();
beelzebup = bufferedReader.readLine();
astaroth = bufferedReader.readLine();
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
float temp = 0;
int n;
for(int i=0; i < uniqueAddress.size(); i++) {
for(int j=0; j < listAddress.size(); j++) {
if(uniqueAddress.get(orderAddress.get(i)).equals(listAddress.get(j))) {
temp++;
}
}
if(temp >= 6) {
temp = temp + temp/3;
}
if(astaroth.equals(uniqueAddress.get(orderAddress.get(i))) || lucifer.equals(uniqueAddress.get(orderAddress.get(i))) || beelzebup.equals(uniqueAddress.get(orderAddress.get(i)))) {
temp += 11;
}
n = (int) temp;
totalNfts += n;
nfts.put(uniqueAddress.get(orderAddress.get(i)), temp);
temp = 0;
}
}
public void calculus() {
float temp = (float) 0;
try(FileWriter fw = new FileWriter("rewards.txt", true)){
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < orderAddress.size(); i++) {
temp = nfts.get(orderAddress.get(i))/totalNfts*cifra;
System.out.println(orderAddress.get(i)+","+temp);
bw.write(orderAddress.get(i)+","+temp);
temp = 0;
}
bw.close();
}
catch(IOException e){
// handle the exception
}
}
}``
Maybe your code produces an exception before the file could be written. You could try the following to narrow down the problem (if you are not comfortable with using a debugger):
public void calculus() {
float temp = (float) 0;
String baseDir = "C:/Users/..../folder";
try(FileWriter fw = new FileWriter(baseDir + "rewards.txt", true)){
BufferedWriter bw = new BufferedWriter(fw);
// check if this string will be present in
// your file
bw.write("Test");
// this will force the BufferedWriter to
// write to the file immediately
bw.flush();
System.out.println("orderAddress.size() = " + orderAddress.size());
for(int i = 0; i < orderAddress.size(); i++) {
temp = nfts.get(orderAddress.get(i))/totalNfts*cifra;
System.out.println(orderAddress.get(i)+","+temp);
bw.write(orderAddress.get(i)+","+temp);
temp = 0;
// this will force the BufferedWriter to
// write to the file immediately
bw.flush();
}
bw.close();
}
catch(IOException e){
// 1
System.err.println(e);
// 2
throw new RuntimeException("IOException occurred" +
" while trying to write to file.", e);
}
}
I added some lines...
First, I added a new variable baseDir where you can set the path to the folder in which the file should be created.
bw.write("Test"); checks if "Test" will appear in your file. Then I added bw.flush(); twice. This force the BufferedWriter to immediately write to the file. If an exception occurred in the for-loop, your file will still contain the last working execution.
In the catch-block you should handle your exception in some way. I provided you with two of many other possibilities:
If you want your program to continue when an exception occurs, you can just print the exception to the console, so you would still be aware of it.
If you want your program to stop when an exception occurs, you can throw a RuntimeException
I have two text files. I have to develop a java program which compares the two files and find unique words. I have tried a few methods but didn’t work. Example:
test1.txt:
I am a robot. My name is Sofia.
test2.txt:
Hello I am a man. My name is Alex
Output:
Hello robot man Sofia Alex
I approach was like this:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("test1.txt"));
Scanner scan = new Scanner(new File("test2.txt"));
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> a2 = new ArrayList<String>();
String test;
while (input.hasNext()) {
String next = input.next();
}
System.out.println("arraylist" + al);
while (scan.hasNext()) {
test = scan.next();
a2.add(test);
}
System.out.println("arraylist2" + a2);
for( int i = 0; i < al.size(); i++){
for(int j = 0; j < a2.size(); j++){
if(al.get(i).equals(a2.get(j))){
break;}
else{
System.out.println(al.get(i));break;
}
}
}
}
}
Note that this is a quick and dirty approach and pretty inefficient. Furthermore I dont know your exact requirements (full stops? Upper/lowercase?).
Also take into account that this program doesn't check which list is longer. But this should give you a good hint:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("test1.txt"));
Scanner scan = new Scanner(new File("test2.txt"));
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
while (input.hasNext()) {
list1.add(input.next());
}
while (scan.hasNext()) {
list2.add(scan.next());
}
// iterate over list 1
for (int i = list1.size() - 1; i >= 0; i--) {
// if there is a occurence of two identical strings
if (list2.contains(list1.get(i))) {
// remove the String from list 2
list2.remove(list2.indexOf(list1.get(i)));
// remove the String from list 1
list1.remove(i);
}
}
// merge the lists
list1.addAll(list2);
// remove full stops
for (int i = 0; i < list1.size(); i++) {
list1.set(i, list1.get(i).replace(".", ""));
}
System.out.println("Unique Values: " + list1);
}
}
Assumptions are the text file contains only (.) as sentence terminator.
public static void main(String[] args) throws Exception
{
// Skipping reading from file and storing in string
String stringFromFileOne = "I am a robot. My name is Sofia.";
String stringFromFileTwo = "Hello I am a man. My name is Alex";
Set<String> set1 = Arrays.asList(stringFromFileOne.split(" "))
.stream()
.map(s -> s.toLowerCase())
.map(m -> m.contains(".") ? m.replace(".", "") : m)
.sorted()
.collect(Collectors.toSet());
Set<String> set2 = Arrays.asList(stringFromFileTwo.split(" "))
.stream()
.map(s -> s.toLowerCase())
.map(m -> m.contains(".") ? m.replace(".", "") : m)
.sorted()
.collect(Collectors.toSet());
List<String> uniqueWords;
if (set1.size() > set2.size()) {
uniqueWords = getUniqueWords(set2, set1);
} else {
uniqueWords = getUniqueWords(set1, set2);
}
System.out.println("uniqueWords:" + uniqueWords);
}
private static List<String> getUniqueWords(Set<String> removeFromSet, Set<String> iterateOverSet) {
List<String> uniqueWords;
Set<String> tempSet = new HashSet<String>(removeFromSet);
removeFromSet.removeAll(iterateOverSet);
uniqueWords = iterateOverSet.stream().filter(f -> !tempSet.contains(f) && !f.isEmpty())
.collect(Collectors.toList());
uniqueWords.addAll(removeFromSet);
return uniqueWords;
}
You can use guava library which gives you difference between two sets.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import com.google.common.collect.Sets;
public class WordTest {
public static void main(String[] args) {
WordTest wordTest = new WordTest();
Set<String> firstFileWords = wordTest.getAllWords("E:\\testing1.txt");
Set<String> secondFileWords = wordTest.getAllWords("E:\\testing2.txt");
Set<String> diff = Sets.difference(firstFileWords, secondFileWords);
Set<String> diff2 = Sets.difference(secondFileWords, firstFileWords);
System.out.println("Set 1: " + firstFileWords);
System.out.println("Set 2: " + secondFileWords);
System.out.println("Difference between " + "Set 1 and Set 2: " + diff);
System.out.println("Difference between " + "Set 2 and Set 1: " + diff2);
}
public Set<String> getAllWords(String path) {
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Set<String> wordList = new HashSet<>();
try {
fis = new FileInputStream(path);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " ,.;:\"");
while (st.hasMoreTokens()) {
wordList.add(st.nextToken());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (Exception ex) {
}
}
return wordList;
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
public class FileComparision {
public static void main(String[] args) throws IOException {
HashSet<String> uniqueSet=new HashSet<String>();
//split the lines based on the delimiter and add it to set
BufferedReader reader=new BufferedReader(new FileReader("test1.txt"));
String line;
while ((line = reader.readLine()) != null) {
Arrays.asList(line.split(" ")).forEach(word->uniqueSet.add(word) ); ;
}
reader.close();
reader=new BufferedReader(new FileReader("test2.txt"));
while ((line = reader.readLine()) != null) {
Arrays.asList(line.split(" ")).forEach(word->{
if(!uniqueSet.contains(word)) {
uniqueSet.add(word) ;
}else {
uniqueSet.remove(word);
}
});
}
reader.close();
//to remove unnecessary characters
//uniqueSet.remove(".");
System.out.println(uniqueSet);
}
}
public static String readFile(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception
{
String data = readFileAsString("C:\\Users\\pb\\Desktop\\text1.txt");
String data1 = readFileAsString("C:\\Users\\pb\\Desktop\\text2.txt");
String array[]=data.split(" ");
String array1[]=data1.split(" ");
for(int i=0;i<=array1.length-1;i++){
if(data.contains(array1[i])){
}else{
System.out.println(array1[i]);
}
}
for(int i=0;i<=array.length-1;i++){
if(data1.contains(array[i])){
}else{
System.out.println(array[i]);
}
}
}
so the full program reads a story from a file and stores each word in an array of strings. After the story is read, I need to print all unique words in the story but I don't know how. Here is what I have
import java.util.*;
import csci1140.*;
import java.io.*;
public class Story{
public static final void main(String[] args){
String[] storyArray = new String[28203];
String fileName = "MultiLineStory.txt";
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(fileName));
}catch(FileNotFoundException fnfe){
System.out.println("Unable to find file: " + fileName);
}
try{
String input = null;
for(int i = 0; i < storyArray.length; i++){
if((input = reader.readLine()) != null){
String fill = input;
storyArray[i] = fill;
}
// System.out.print(storyArray[i] + " ");
}
} catch(IOException ioe){
ioe.printStackTrace(System.err);
} finally {
try{
reader.close();
}catch(Exception e){}
}
long start = System.nanoTime();
Arrays.sort(storyArray);
long end = System.nanoTime();
System.out.println("\n\nArrays.sort took " +((end - start)/1E9) + " Sec");
distinctValues(storyArray);
}
public static boolean distinctValues(String[] array){
int count = 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] == array[i + 1]) {
count++;
return true;
}
}
System.out.println(count);
return false;
}
}
You can use a HashSet<String> and put all elements of the array into it. Then just print them out one by one.
String[] allWordsArray = ...;
HashSet<String> uniqueWordsSet = new HashSet<>(Arrays.asList(allWordsArray));
for (String word : uniqueWordsSet)
{
System.out.println(word);
}
Try this:
package com;
import java.util.*;
import java.io.*;
/*to print unique words which are not repeated*/
public class UniqueWords {
public static final void main(String[] args){
ArrayList<String> allWords = new ArrayList<String>();
Map<String, Integer> map = new HashMap<String, Integer>();
String fileName = "C:\\TestFiles\\MultiLineStory.txt";
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(fileName));
String input = null;
if((input = reader.readLine()) != null){
String arr[] = input.split(" ");
allWords.addAll(Arrays.asList(arr));
}
System.out.println(allWords.size());
}catch(FileNotFoundException fnfe){
System.out.println("Unable to find file: " + fileName);
} catch(IOException ioe){
ioe.printStackTrace(System.err);
} finally {
try{
reader.close();
}catch(Exception e){}
}
for(String word : allWords)
{
if(!map.containsKey(word))
map.put(word, 1);
else
map.put(word, map.get(word)+1);
}
Set<String> keySet = map.keySet();
for(String key : keySet)
if(map.get(key)==1)
System.out.println(key);
}
}
I saw some similar questions, but mine is a little different.
I define a
Map<Integer, ArrayList<Double>> fl;
My input .txt file:
1 0.56 0.57 0.73 ..
2 2.3 3.50 ...
9 4.98 0.99 ..
How to read the file into the map fl?
Thanks!
Use a Scanner and first call Scanner.readInt() that will give you the first integer.
Then call Scanner.readLine() that will give you all the remaining double in the line as a String. Split it and parse everything to double.
Repeat the same till end of file.
Here's a try.
I've compiled and run the code.
Make sure the input file is in the same directory as your project if you use an IDE.-- This only applies if you do not modify the path below.
package fileread;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class FileRead {
private static HashMap<Integer, ArrayList<Double>> map = new HashMap<>();
private static BufferedReader reader;
public static void main(String[] args) {
try
{
reader = new BufferedReader(new FileReader("input"));
//or reader = new BufferedReader(new FileReader("C:\\full-path-to-your-file));
String line;
while((line = reader.readLine()) != null)
{
String[] tokens = line.split(" ");
Integer i;
Double d;
ArrayList<Double> list = new ArrayList<>();
i = Integer.valueOf(tokens[0]);
for(int j = 1; j < tokens.length; j++)
list.add(Double.valueOf(tokens[j]));
map.put(i, list);
}
}catch(IOException ex)
{
//break execution
}finally
{
if(reader != null)
try
{
reader.close();
}catch (IOException ex) {
//don't break :)
}
}
for(Integer i : map.keySet())
{
ArrayList<Double> l = map.get(i);
System.out.print("Line " + i + ": ");
for(Double d: l)
System.out.print(d + " ");
System.out.println();
}
}
}
The code for parsing the file and populating the map should be like below
try {
BufferedReader bReader = new BufferedReader(new FileReader(new File("c:/input .txt")));
String line = "";
Map<Integer, ArrayList<Double>> fl = new HashMap<Integer, ArrayList<Double>>();
while ((line = bReader.readLine()) != null) {
String[] strArray = line.split(" ");
for (int i=0;i<strArray.length;i++) {
ArrayList<Double> value = new ArrayList<Double>();
int key=0;
if(i==0){
key =Integer.valueOf(strArray[0]);
}
else{
value.add(Double.valueOf(strArray[i]));
}
fl.put(key, value);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So here I have code I have HashMap made up by the words in file, I am adding words and writing them on file and it works, but when I use my remove function for some reaseon doesnt do anything here is the code :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
public static int value = 1;
private static Scanner input;
public static Scanner in = new Scanner(System.in);
public static Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) throws FileNotFoundException {
readFile();
System.out.println("Enter number of function wanted" + "\n1 to add"
+ "\n2 for searching by prefix" + "\n3 for deleting");
int choice = in.nextInt();
if (choice == 1) {
System.out.println("enter words seprated by comma");
String wd = in.next();
add(wd);
}
if (choice == 2) {
System.out.println("Enter prefix");
String wd = in.next();
prefixSearch(wd);
}
if (choice == 3) {
System.out.println("ENTER word to delete");
String wd = in.next();
remove(wd);
}
}
public static void readFile() throws FileNotFoundException {
input = new Scanner(file);
boolean done = false;
int value = 1;
while (input.hasNext()) {
String word = input.next().toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.put(line[j], value);
value++;
done = true;
}
}
if (done == true) {
System.out.println("Succes");
}
}
public static void prefixSearch(String wd) {
System.out.println("Enter prefix");
String prefix = wd.toLowerCase();
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().startsWith(prefix)) {
System.out.println(key.getKey());
}
}
}
public static void add(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
if (!map.containsKey(line[j])) {
map.put(line[j], value);
value++;
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
if (done == true) {
System.out.println("Success");
}
}
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().equals(line[j])) {
map.remove(key.getKey(), key.getValue());
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
}
if (done == true) {
System.out.println("Succes");
}
}
}
Every other method is working just fine, but remove. Is there something wrong with the loops, maybe use more optimal way or?
The reason for failure is that you're trying to change the map while iterating the entries. As with any collection - if you try to modify it while iterating it you'll get ConcurrentModificationException.
Further, there's a redundant inner for-loop (redundant because the whole purpose of a map is that you won't have to iterate it when you're looking for a specific value/s) which means that you'll try to override the file many times when only once is sufficient.
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.remove(line[j]);
}
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
if (done == true) {
System.out.println("Success");
}
}
The issues that I can see in your code are the following:
You forgot a quote when defining the file:
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt")
should be:
public static File file = new File("C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
The remove() function in a map receives only one parameter, which is the key of the entry you want to remove, so:
map.remove(key.getKey(), key.getValue());
should be:
map.remove(key.getKey());
Also, since your getting the entrySet of your map, maybe you should consider renaming the key variable in the rename() function to entry.