number of lines is equal to number of names - java

if anyone can help me please in java programme , I have file called "input.txt" which contains text like
Agent1 R F 2 0
Agent2 R B 4 5
Agent4 C E 2 2
Agent3 R F 3 11
I want to save all the lines in different variable and do work on them.
say here I want to save the first line into string which I will call line1, second line I will save in string called line2 third line I will save on string called line3 and so on.
is their any way to do that. my txt file can have any number of line and I want to save those lines as strings do work on them.
simply I need something like a loop which will keep on changing the name of variable . but i have no idea how to do it.
here is my code till now but instead of output i want to save lines as string of any data type
any help really appreciated.

You cannot create variables at the fly, like you mentioned just by changing the name. You can use List for storing the data from file and process it later.
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
List<String> names = new ArrayList<String>();
while (scanner.hasNext()) {
String line = scanner.nextLine();
names.add(line);
}
// Now all the lines from the file are stored in the list.
// You can do the processing you need to do.
Convert the List of Strings into String array and use the Arrays.sort method for sorting the array. We will provide the custom Comparator to sort the array as per our needs.
String nameArray[] = names.toArray(new String[names.size()]);
Arrays.sort(nameArray, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
String array1[] = o1.split(" ");
String array2[] = o2.split(" ");
return array1[3].compareTo(array2[3]);
}
});
The assumption here is lines will always contain the five elements and we are sorting by fourth position number in the line.
output:
Agent1 R F 2 0
Agent4 C E 2 2
Agent3 R F 3 11
Agent2 R B 4 5

Try this.
public static Map<String, String> loadFile(Reader reader)
throws IllegalArgumentException{
Map<String, String> mapList = new TreeMap<String, String>();
if(reader == null)
{
throw new IllegalArgumentException("Reader not valid");
}
String line;
innerReader = new BufferedReader(reader);
int countLine = 0;
try
{
while((line = innerReader.readLine()) != null)
{
if (line == null || line.trim().isEmpty())
throw new IllegalArgumentException(
"Line Empty");
mapList.put("line"+String.valueOf(countLine), line);
countLine++;
}
} catch (IOException e) {
}
return mapList;
}
In main add this to try your code.
Map<String, String> mapList = new TreeMap<String, String>(Collections.reverseOrder());
try {
mapList = loadFile(new FileReader("YourFile.txt"));
} catch (IOException e) {
e.printStackTrace();
}
for (Map.Entry entry : mapList.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
Ann this is output.
line0, Agent1 R F 2 0
line1, Agent2 R B 4 5
line2, Agent4 C E 2 2
line3, Agent3 R F 3 11
For print out in file add this:
private static PrintWriter innerWriter;
public static void printMap(Map<String, String> myMap, Writer writer)
throws IOException {
if(writer == null)
{
throw new IOException("Cannot open file");
}
innerWriter = new PrintWriter(writer);
for (Map.Entry entry : myMap.entrySet()) {
innerWriter.write(entry.getKey() + ", " + entry.getValue() + "\n");
//OR THIS FOR ONLY VALUES
// innerWriter.write(entry.getValue() + "\n");
}
innerWriter.close();
}
and this on main
try {
printMap(mapList, new FileWriter("FileOutput.txt"));
} catch (IOException e) {
e.printStackTrace();
}

Related

Find the line number of a text file by each word

I want to find the line number of a text file by each word, however, the method I wrote below only gives the first number while I need a list of line numbers.
For instance, if "a" occurs in lines: 1,3,5, it should have a list of [1,3,5]. This list result then will be passed into another method for further process. But, my result only shows [1] for "a".
Can someone help me fix this? Thank you!
public SomeObject<Word> buildIndex(String fileName, Comparator<Word> comparator) {
SomeObject<Word> someObject = new SomeObject<>(comparator);
Comparator<Word> comp = checkComparator(someObject.comparator());
int num = 0;
if (fileName != null) {
File file = new File(fileName);
try (Scanner scanner = new Scanner(file, "latin1")) {
while (scanner.hasNextLine()) {
String lines;
if (comparator instanceof IgnoreCase) {
lines = scanner.nextLine().toLowerCase();
} else {
lines = scanner.nextLine();
}
if (lines != null) {
String[] lineFromText = lines.split("\n");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < lineFromText.length; i++) {
String[] wordsFromText = lineFromText[i].split("\\W");
num++;
for (String s : wordsFromText) {
if (s != null && lineFromText[i].contains(s)) {
list.add(num);
}
if (s != null && !s.trim().isEmpty() && s.matches("^[a-zA-Z]*$")) {
doInsert(s, comp, someObject, list);
}
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return someObject;
}
Does something like this work for you?
It reads in the lines one at a time.
Finds the words by splitting on spaces.
Then puts the words and the line numbers in a map where the
key is the word an the value is a list of line numbers.
int lineCount = 1;
String fileName = "SomeFileName";
Map<String, List<Integer>> index = new HashMap<>();
Scanner scanner = new Scanner("fileName");
while (scanner.hasNextLine()) {
//get single line from file
String line = scanner.nextLine().toLowerCase();
//split into words
for (String word : line.split("\\s+")) {
// add to lineNumber to map if List already there.
// otherwise add new List and then add lineNumber
index.compute(word,
(wd, list) -> list == null ? new ArrayList<>()
: list).add(lineCount);
}
// bump lineCount for next line
lineCount++;
}
Print them out.
index.forEach((k, v) -> System.out.println(k + " --> " + v));

Reading input from a file in Java

I am having the following file have 3 columns , i want read the following file and store them ArrayList , how to read it using Scanner or Buffer reader ?
For Example.
ArrayList<Integert>[][] M = new ArrayList[size][size]
M[1][859].add(1806476)
M[3][800].add(2131700)
M[3][800].add(2734107).. so one
A B C
1 859 [1806476]
3 800 "[2131700, 2734107, 2877209, 2877209]"
4 815 [2883211]
7 815 "[2429412, 2886810, 2886804]"
7 362 [2909301]
7 806 [89573]
7 853 [2182646]
8 800 "[2910937, 2836340, 2884417]"
Basically you want to store it in arrayList. You can use below approach
create a class of fields
class Multi {
int a, b, c;
}
public void addrecords(int i, int j, int k) {
Multi multi = new Multi();
Multi.a = i;
Multi.b = j;
Multi.c = k;
records.add(Multi);
}
List<Multi> records;
//code goes here
private static void parseInput(Map<Pair<Integer, Integer>, List<Integer>> data, String line) {
String[] tmp = line.split(" ");
String result = line.substring(tmp[0].length() + tmp[1].length() + 2);
result = result.replaceAll("\"", "");
result = result.replace(",", "");
result = result.replace("[", "");
result = result.replace("]", "");
List<Integer> t = new ArrayList<>();
for (String a: result.split(" "))
t.add(Integer.parseInt(a));
data.put(new Pair<>(Integer.parseInt(tmp[0]), Integer.parseInt(tmp[1])), t);
}
BufferedReader reader = null;
FileReader fileReader = null;
try {
fileReader = new FileReader("in.txt");
reader = new BufferedReader(fileReader);
String line;
Map<Pair<Integer, Integer>, List<Integer>> data = new HashMap<>();
while ((line = reader.readLine()) != null) {
parseInput(data, line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
if (fileReader != null)
fileReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
plus add try/catch block when u parse String to Integer

Reading Unique Values

I wrote a piece of code that reads values from columns in a text file. To output the number of values, I used 'length' which works fine..but I need to count only the number of unique values.
public class REading_Two_Files {
public static void main(String[] args) {
try {
readFile(new File("C:\\Users\\teiteie\\Desktop\\RECSYS\\yoochoose-test.csv"), 0,( "C:\\Users\\teiteie\\Desktop\\RECSYS\\yoochoose-buys.csv"), 3);
//readFile(new File(File1,0, File2,3);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//// 0 - will print column from file1
//3 - will print column from file 2
private static void readFile(File fin1,int whichcolumnFirstFile,String string,int whichcolumnSecondFile) throws IOException {
//private static void readFile(File fin1,int whichcolumnFirstFile,String string,int whichcolumnSecondFile) throws IOException
// code for this method.
//open the two files.
int noSessions = 0;
int noItems = 0;
// HashSet<String> uniqueLength = new HashSet<String>();
FileInputStream fis = new FileInputStream(fin1); //first file
FileInputStream sec = new FileInputStream(string); // second file
//Construct BufferedReader from InputStreamReader
BufferedReader br1= new BufferedReader(new InputStreamReader(fis));
BufferedReader br2= new BufferedReader(new InputStreamReader(sec));
String lineFirst = null, first_file[];
String lineSec = null, second_file [];
while ((lineFirst = br1.readLine()) != null && (lineSec = br2.readLine()) != null) {
first_file= lineFirst.split(",");
second_file = lineSec.split(",");
//int size = data[].size();
System.out.println(first_file[0]+" , "+second_file[0]);
if(first_file.length != 0){
noSessions++;
}
if(second_file.length != 0) {
noItems ++;
}
}
br1.close();
br2.close();
System.out.println("no of sessions "+noSessions+"\nno of items "+noItems );
}
}
To count only unique values we usually use a Set as they are specified as only containing unique values.
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
Essentially - put all of your values in a Set (generally a HashSet is the most efficient but if you want concurrency there are better options) and then take the Set.size() as the number of unique values you put in.
just to give you some inspiration:
Map<String,Integer> lAllWordsWithCount = new HashMap<String, Integer>();
String[] lAllMyStringToCount = {"Hello", "I", "am", "what", "I", "am"};
for (String lMyString : lAllMyStringToCount) {
int lCount = 1;
if (lAllWordsWithCount.containsKey(lMyString)){
lCount = lAllWordsWithCount.get(lMyString) +1;
}
lAllWordsWithCount.put(lMyString, lCount);
}
for(String lStringKey : lAllWordsWithCount.keySet()){
System.out.println(lStringKey+" count="+lAllWordsWithCount.get(lStringKey));
}
will results in:
what count=1
am count=2
I count=2
Hello count=1

how to get specifics rows of 2d array returned by reading CSV file in java

This is data.csv file, now I want rows having classtype x (any number) and store those extarcted rows into new array, so if i have n classtype then i will have n new arrays.
age sex zipcode classtype
21 m 23423 1
12 f 23133 2
23 m 32323 2
23 f 23211 1
Example: If I want to retrieve rows which have classtype 1 and store this values in a new 2d array. Then output should come like this:
array1={{21,m,23423,1},{23,f,23211,1}}
I have written the below code which gives me arrayList as output.
public class CsvParser {
public static void main(String[] args) {
try {
FileReader fr = new FileReader((args.length > 0) ? args[0] : "data.csv");
Map<String, List<String>> values = parseCsv(fr, "\\s,", true);
System.out.println(values);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<String, List<String>> parseCsv(Reader reader, String separator, boolean hasHeader) throws IOException {
Map<String, List<String>> values = new LinkedHashMap<String, List<String>>();
List<String> columnNames = new LinkedList<String>();
BufferedReader br = null;
br = new BufferedReader(reader);
String line;
int numLines = 0;
while ((line = br.readLine()) != null) {
if (StringUtils.isNotBlank(line)) {
if (!line.startsWith("#")) {
String[] tokens = line.split(separator);
if (tokens != null) {
for (int i = 0; i < tokens.length; ++i) {
if (numLines == 0) {
columnNames.add(hasHeader ? tokens[i] : ("row_"+i));
} else {
List<String> column = values.get(columnNames.get(i));
if (column == null) {
column = new LinkedList<String>();
}
column.add(tokens[i]);
values.put(columnNames.get(i), column);
}
}
}
++numLines;
}
}
}
return values;
}
The ouput of this code is:
{age=[21,12,23,23],sex=[m,f,m,f],zipcode=[23423,23133,32323,23211],classtype=[1,2,2,1]}
I got few links, which says about grouping elements in "java collectors class", But dont whether that is useful.
http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-
Your help will be very useful.
You can try something like
String[][] allArrays = new String[50][]; //Set it to however many you need
String classType = "1";
int counter = 0;
Scanner s = new Scanner(new File(fileName));
while(s.hasNextLine()) {
String row = s.nextLine();
if (row.endsWith(classType) {
allArrays[counter++] = row.split(","); //Adds the row, with each element being split by the comma
}
}
Do not reinvent the wheel, you can use an existing library to dump the content of CSV file to a Java Collection. I usually use OpenCSV to dump the contents of CSV file to List<String[]>. It has a one liner code to read all.
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List<String[]> lines= reader.readAll();
Then iterate the list like this to do the grouping.
Map<String, List<String[]>> values = new LinkedHashMap<String, List<String[]>>();
for(String[] line : lines){
String key = line[4];
if(values.get(key) == null){
values.put(key, new ArrayList<String[]>());
}
values.get(key).add(line);
}
System.out.println(values);

Combining a line counter method with a word counting method

I have a method that counts the occurrences of words in a text file, and returns the number of time the word is found on a particular line. However, it doesn't keep track of which line number the words are located. i have a separate method that counts the number of lines in the text file and i would like to combine the two methods into a method that tracks the line numbers, and keeps a log of the words occurrences on each line.
here are the two methods i would like to combine to give a result something like "Word occurs X times on line Y"
public class Hash
{
private static final Object dummy = new Object(); // dummy variable
public void hashbuild()
{
File file = new File("getty.txt");
// LineNumberReader lnr1 = null;
String line1;
try{
Scanner scanner = new Scanner(file);
//lnr1 = new LineNumberReader(new FileReader("getty.txt"));
// try{while((line1 = lnr1.readLine()) != null)
// {}}catch(Exception e){}
while(scanner.hasNextLine())
{
String line= scanner.nextLine();
List<String> wordList1 = Arrays.asList(line.split("\\s+"));
Map<Object, Integer> hm = new LinkedHashMap<Object, Integer>();
for (Object item : wordList1)
{
Integer count = hm.get(item);
if (hm.put(item, (count == null ? 1 : count + 1))!=null)
{
System.out.println("Found Duplicate : " +item);
}
}
for ( Object key : hm.keySet() )
{
int value = hm.get( key );
if (value>1)
{
System.out.println(key + " occurs " + (value) + " times on line # "+lnr1.getLineNumber());
}
}
}
} catch (FileNotFoundException f)
{f.printStackTrace();}
}
}
here is my original line counting method
public void countLines()
{
LineNumberReader lnr = null; String line;
try
{
lnr = new LineNumberReader(new FileReader("getty.txt"));
while ((line = lnr.readLine()) != null)
{
System.out.print("\n" +lnr.getLineNumber() + " " +line);
}
System.out.println("\n");
}catch(Exception e){}
}
Why don't you just remember the line number in the while loop? Initialize a new variable and increase it when calling nextline.

Categories

Resources