Inserting a text file into a Map<Integer, Map<Integer, Double>> - java

This is my first question here so please bear with me. I have a text file that looks like something like this;
userId,itemId,rating
1,101,2.5
4,103,3.0
1,103,3.0
6,104,3.5
2,101,3.0
4,106,4.5
2,103,1.5
5,102,4.0
2,105,3.5
7,106,3.0
3,101,2.5
3,102,3.0
What I'am trying to accomplish is to read the file line per line and seperated each value. After that is done place all unique userIds in the key section of this map; Map<Integer, Map<Integer, Double>>. And place the itemIds with the rating in the second map corresponding to the key of the first map. Can you still follow me?? Here is the code I produced so far with not the outcome I want.
This is my User class:
package com.example;
import java.util.HashMap;
import java.util.Map;
public class User {
private int mUserId;
private Map<Integer, Double> mRatedItems;
public User(int userId) {
mUserId = userId;
mRatedItems = new HashMap<>();
}
public int getUserId() {
return mUserId;
}
public void setUserId(int userId) {
mUserId = userId;
}
public Map<Integer, Double> getRatedItems() {
return mRatedItems;
}
public void addRatedItems(int itemId, double rating) {
mRatedItems.put(itemId, rating);
}
}
This is the file I need to modify:
package com.example;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class TextFile {
List<User> mUserIdList;
private User mUser;
public Map<Integer, Map<Integer, Double>> readFile(String fileName) {
mUserIdList = new ArrayList<>();
Map<Integer, Map<Integer, Double>> userItemData = new HashMap<>();
try (
FileInputStream fis = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis))
) {
String line;
while ((line = reader.readLine()) != null) {
String[] args = line.split(",");
int userId = Integer.parseInt(args[0]);
int itemId = Integer.parseInt(args[1]);
double rating = Double.parseDouble(args[2]);
if (!mUserIdList.contains(userId)) {
mUser = new User(userId);
mUserIdList.add(mUser);
}
if (!mUserIdList.isEmpty()) {
addItemRatings(userId, itemId, rating);
}
if (!checkDuplicates()) {
userItemData.put(mUser.getUserId(), mUser.getRatedItems());
}
}
} catch (IOException e) {
System.out.printf("Problem loading: %s %n", fileName);
e.printStackTrace();
}
return userItemData;
}
private boolean checkDuplicates() {
Set<Integer> set = new HashSet<>();
for (User user : mUserIdList) {
if (!set.add(user.getUserId())) {
return true;
}
}
return false;
}
public void addItemRatings(int userId, int itemId, double rating) {
for (User user : mUserIdList) {
if (user.getUserId() == userId) {
user.addRatedItems(itemId, rating);
}
}
}
public int showTextLines(String fileName) {
int textLines = 0;
try (
FileInputStream fis = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis))
) {
while (reader.readLine() != null) {
textLines++;
}
reader.close();
} catch (IOException e) {
System.out.printf("Problem showing total lines from: %s %n", fileName);
e.printStackTrace();
}
return textLines;
}
}
This is my main class:
package com.example;
import java.util.Map;
public class Main {
public static void main(String[] args) {
TextFile textFile = new TextFile();
String location = "D:\\IdeaProjects\\KMeans\\src\\com\\quincy\\userItem1.data";
Map<Integer, Map<Integer, Double>> readFile = textFile.readFile(location);
int textLines = textFile.showTextLines(location);
System.out.printf("File: %s %n", readFile);
System.out.printf("Number of lines in file: %s %n", textLines);
}
}
And my output is:
File: {1={101=2.5, 103=3.0}, 4={103=3.0, 106=4.5}}
Number of lines in file: 12
My code is only adding the first two userIds with their corresponding itemIds and rating. Can somebody please explain to me what I' am doing wrong?? And maybe show how I can improve this code to work properly??
Thanks in advance.

The problem is in your checkDuplicates() method. I don't know what exactly you're trying to achieve on that function but if you want to check for duplications. then, I suggest you just use the function containsKey() like this.
if (!userItemData.containsKey(mUser.getUserId())) {
userItemData.put(mUser.getUserId(), mUser.getRatedItems());
}

Related

How can I sort a Ranking list using a specific column from a file and print the whole file sorted?Java

Already done this but can't make it work.
Also tried to create another while ((line = br.readLine()) != null) {}, and placed the sort before it, but it won't read this while so it wouldnt print anithing.
The file looks like this:
1-Fred-18-5-0
2-luis-12-33-0
3-Helder-23-10-0
And wanted it to print like this:
2-luis-12-33-0
3-Helder-23-10-0
1-Fred-18-5-0
public static void lerRanking() throws IOException {
File ficheiro = new File("jogadores.txt");
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<Integer> jGanhos = new ArrayList<Integer>();
int i = 0;
String line;
String texto = "";
while ((line = br.readLine()) != null) {
String[] col = line.split("-");
int colunas = Integer.parseInt(col[3]);
jGanhos.add(colunas);
i++;
if(i>=jGanhos.size()){
Collections.sort(jGanhos);
Collections.reverse(jGanhos);
for (int j = 0; j < jGanhos.size(); j++) {
if(colunas == jGanhos.get(i)){
texto = texto + line + "\n";
}
}
}
}
PL(texto);
}
Make it step by step:
public static void lerRanking() throws IOException {
File ficheiro = new File("jodagores.txt");
// read file
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<String> lines = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
// sort lines
lines.sort(new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// sort by 3rd column descending
return Integer.parseInt(s2.split("-")[3]) - Integer.parseInt(s1.split("-")[3]);
}
});
// concat lines
String texto = "";
for (String l : lines) {
texto += l + "\n";
}
System.out.println(texto);
// PL(texto);
}
Okay so first of all I thounk you should introduce a Java class (in my code this is ParsedObject) to manage your objects.
Second it should implement the Comparable<ParsedObject> interface, so you can easily sort it from anywhere in the code (without passing a custom comparator each time).
Here is the full code:
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
lerRanking();
}
public static void lerRanking() throws IOException {
File ficheiro = new File("jodagores.txt");
// read lines to a list
List<String> lines = readLines(ficheiro);
// parse them to a list of objects
List<ParsedObject> objects = ParsedObject.from(lines);
// sort
Collections.sort(objects);
// print the output
writeLines(objects);
}
public static List<String> readLines(File ficheiro) throws IOException {
// read file line by line
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<String> lines = new ArrayList<>();
String line;
while((line = br.readLine()) != null) {
lines.add(line);
}
br.close(); // THIS IS IMPORTANT never forget to close a Reader :)
return lines;
}
private static void writeLines(List<ParsedObject> objects) throws IOException {
File file = new File("output.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(ParsedObject object : objects) {
// print the output line by line
bw.write(object.originalLine);
}
bw.flush();
bw.close(); // THIS IS IMPORTANT never forget to close a Writer :)
}
// our object that holds the information
static class ParsedObject implements Comparable<ParsedObject> {
// the original line, if needed
public String originalLine;
// the columns
public Integer firstNumber;
public String firstString;
public Integer secondNumber;
public Integer thirdNumber;
public Integer fourthNumber;
// parse line by line
public static List<ParsedObject> from(List<String> lines) {
List<ParsedObject> objects = new ArrayList<>();
for(String line : lines) {
objects.add(ParsedObject.from(line));
}
return objects;
}
// parse one line
public static ParsedObject from(String line) {
String[] splitLine = line.split("-");
ParsedObject parsedObject = new ParsedObject();
parsedObject.originalLine = line + "\n";
parsedObject.firstNumber = Integer.valueOf(splitLine[0]);
parsedObject.firstString = splitLine[1];
parsedObject.secondNumber = Integer.valueOf(splitLine[2]);
parsedObject.thirdNumber = Integer.valueOf(splitLine[3]);
parsedObject.fourthNumber = Integer.valueOf(splitLine[4]);
return parsedObject;
}
#Override
public int compareTo(ParsedObject other) {
return other.thirdNumber.compareTo(this.thirdNumber);
}
}
}
If you have any more question feel free to ask :) An here is an the example objects list after parsing and sorting.
The easiest way is to first create a class that will hold the data from your file provided your lines keep the same format
public class MyClass {
private Integer column1;
private String column2;
private Integer column3;
private Integer column4;
private Integer column5;
public MyClass(String data) {
String[] cols = data.split("-");
if (cols.length != 5) return;
column1 = Integer.parseInt(cols[0]);
column2 = cols[1];
column3 = Integer.parseInt(cols[2]);
column4 = Integer.parseInt(cols[3]);
column5 = Integer.parseInt(cols[4]);
}
public synchronized final Integer getColumn1() {
return column1;
}
public synchronized final String getColumn2() {
return column2;
}
public synchronized final Integer getColumn3() {
return column3;
}
public synchronized final Integer getColumn4() {
return column4;
}
public synchronized final Integer getColumn5() {
return column5;
}
#Override
public String toString() {
return String.format("%d-%s-%d-%d-%d", column1, column2, column3, column4, column5);
}
}
Next you can get a list of your items like this:
public static List<MyClass> getLerRanking() throws IOException {
List<MyClass> items = Files.readAllLines(Paths.get("jogadores.txt"))
.stream()
.filter(line -> !line.trim().isEmpty())
.map(data -> new MyClass(data.trim()))
.filter(data -> data.getColumn4() != null)
.sorted((o1, o2) -> o2.getColumn4().compareTo(o1.getColumn4()))
.collect(Collectors.toList());
return items;
}
This will read your whole file, filter out any blank lines, then parse the data and convert it to MyClass.
It will then make sure that column4 isn't null in the converted objects.
Finally it will reverse sort the objects based off from the value in column 4 and create a list of those items.
To print the results you can do something like this
public static void main(String[] args) {
List<MyClass> rankingList = getLerRanking();
rankingList.forEach(item -> System.out.println(item));
}
Since we overrode the toString() method, it will print it out the object as it is displayed in the file.
Hope this helps.

HASHMAP, key present still giving "false" result

Following is my code that returning false even if the key exists:
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class SequenceNumber {
public static int getSequenceNumber (String TcOrderId){
// Create a hash map to set key values pair.
Map<String, Integer> map = new HashMap<String, Integer>();
int i= 1;
// check if hashmap contains the key.
System.out.println("key present " +map.containsKey(TcOrderId));
if (map.containsKey(TcOrderId))
{
//Key Present
System.out.println("Inside IF ");
int value = map.get(TcOrderId);
System.out.println("value from the key " + value);
map.remove(value);
map.put(TcOrderId, value+1);
return map.get(TcOrderId);
}
else
{
//Key Not present
System.out.println("INSIDE ELSE ");
map.put(TcOrderId, i);
System.out.println("map "+ map);
return map.get(TcOrderId);
}
}
public static void main(String[] args) throws IOException {
String sCurrentLine;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\Users\\BongAn\\Desktop\\Package\\testing.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
while ((sCurrentLine = br.readLine()) != null) {
//String orderid = sCurrentLine.substring(0, 6);
System.out.println("reading line " +sCurrentLine);
int seqvalue = getSequenceNumber(sCurrentLine);
System.out.println("seqvalue "+seqvalue);
}
}
}
}
Input data in the file:
1233
1233
1234
The result should be
1
2
1
But everytime its going in the else loop and the result is
1
1
1
I am trying to use HASHMAP as I am creating my own index.
In your CODE everytime you call getSequenceNumber function - you create new HashMap. I believe this is not something you want.
To avoid that - you can simply move Map<String, Integer> map = new HashMap<String, Integer>(); into the body of class. Since the function getSequenceNumber is a static function - you will need to make the variable static. Hope this helps.
Snippet:
public class SequenceNumber {
// PUT STATIC VARIABLE HERE:
static Map<String, Integer> map = new HashMap<String, Integer>();
public static int getSequenceNumber (String TcOrderId){
// Create a hash map to set key values pair.
// (REMOVE) Map<String, Integer> map = new HashMap<String, Integer>();**
int i= 1;
// check if hashmap contains the key.
...
}
...
}
Another alternative
(perhaps better) would be to avoid static functions and variables and create an instance of SequenceNumber object. That way you could keep a couple of different instance numbers separately.
Simple snippet:
public class SequenceNumber {
// Your hashmap here:
Map<String, Integer> map = new HashMap<String, Integer>();
public int getSequenceNumber (String TcOrderId) {
// ...
}
public static void main(String[] args) throws IOException {
// Instance of SequenceNumber object:
SequenceNumber sequenceNumber = new SequenceNumber();
String sCurrentLine;
BufferedReader br = null;
// ...
while ((sCurrentLine = br.readLine()) != null) {
//String orderid = sCurrentLine.substring(0, 6);
System.out.println("reading line " +sCurrentLine);
int seqvalue = sequenceNumber.getSequenceNumber(sCurrentLine);
System.out.println("seqvalue "+seqvalue);
}
// ...
}
}
Something like this should work. Haven't tried running it though.
public class SequenceNumber {
public static int getSequenceNumber (String TcOrderId, Map<String, Integer> map){
if(!map.contains(TcOrderId)){
map.put(TcOrderId, 0);
}
map.put(TcOrderId, map.get(TcOrderId)+1);
return map.get(TcOrderId);
}
public static void main(String[] args) throws IOException {
String sCurrentLine;
BufferedReader br = null;
Map<String, Integer> map = new HashMap<String, Integer>();
try {
br = new BufferedReader(new FileReader("C:\\Users\\BongAn\\Desktop\\Package\\testing.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
while ((sCurrentLine = br.readLine()) != null) {
//String orderid = sCurrentLine.substring(0, 6);
System.out.println("reading line " +sCurrentLine);
int seqvalue = getSequenceNumber(sCurrentLine, map);
System.out.println("seqvalue "+seqvalue);
}
}

I need to get a file reader to read a text file line by line and format them in Java

I have a text file, formatted as follows:
Han Solo:1000
Harry:100
Ron:10
Yoda:0
I need to make an arrayList of objects which store the player's name (Han Solo) and their score (1000) as attributes. I would like to be able to make this arrayList by reading the file line by line and splitting the string in order to get the desired attributes.
I tried using a Scanner object, but didn't get far. Any help on this would be greatly appreciated, thanks.
You can have a Player class like this:-
class Player { // Class which holds the player data
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
// Getters & Setters
// Overrride toString() - I did this. Its optional though.
}
and you can parse your file which contains the data like this:-
List<Player> players = new ArrayList<Player>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); // I used BufferedReader instead of a Scanner
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(":"); // Split on ":"
players.add(new Player(values[0], Integer.parseInt(values[1]))); // Create a new Player object with the values extract and add it to the list
}
} catch (IOException ioe) {
// Exception Handling
}
System.out.println(players); // Just printing the list. toString() method of Player class is called.
You can create a Class call player. playerName and score will be the attributes.
public class Player {
private String playerName;
private String score;
// getters and setters
}
Then you can create a List
List<Player> playerList=new ArrayList<>();
Now you can try to do your task.
Additionally, you can read from file and split each line by : and put first part as playerName and second part as score.
List<Player> list=new ArrayList<>();
while (scanner.hasNextLine()){
String line=scanner.nextLine();
Player player=new Player();
player.setPlayerName(line.split(":")[0]);
player.setScore(line.split(":")[1]);
list.add(player);
}
If you have Object:
public class User
{
private String name;
private int score;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
}
Make an Reader class that reads from the file :
public class Reader
{
public static void main(String[] args)
{
List<User> list = new ArrayList<User>();
File file = new File("test.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
String[] splitedString = line.split(":");
User user = new User();
user.setName(splitedString[0]);
user.setScore(Integer.parseInt(splitedString[1]));
list.add(user);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
for (User user : list)
{
System.out.println(user.getName()+" "+user.getScore());
}
}
}
The output will be :
Han Solo 1000
Harry 100
Ron 10
Yoda 0
Let's assume you have a class called Player that comprises two data members - name of type String and score of type int.
List<Player> players=new ArrayList<Player>();
BufferedReader br=null;
try{
br=new BufferedReader(new FileReader("filename"));
String record;
String arr[];
while((record=br.readLine())!=null){
arr=record.split(":");
//Player instantiated through two-argument constructor
players.add(new Player(arr[0], Integer.parseInt(arr[1])));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(br!=null)
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
For small files (less than 8kb), you can use this
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class NameScoreReader {
List<Player> readFile(final String fileName) throws IOException
{
final List<Player> retval = new ArrayList<Player>();
final Path path = Paths.get(fileName);
final List<String> source = Files.readAllLines(path, StandardCharsets.UTF_8);
for (final String line : source) {
final String[] array = line.split(":");
if (array.length == 2) {
retval.add(new Player(array[0], Integer.parseInt(array[1])));
} else {
System.out.println("Invalid format: " + array);
}
}
return retval;
}
class Player {
protected Player(final String pName, final int pScore) {
super();
this.name = pName;
this.score = pScore;
}
private String name;
private int score;
public String getName()
{
return this.name;
}
public void setName(final String name)
{
this.name = name;
}
public int getScore()
{
return this.score;
}
public void setScore(final int score)
{
this.score = score;
}
}
}
Read the file and convert it to string and split function you can apply for the result.
public static String getStringFromFile(String fileName) {
BufferedReader reader;
String str = "";
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
str = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) {
String stringFromText = getStringFromFile("C:/DBMT/data.txt");
//Split and other logic goes here
}

Sorting lines in a file by 2 fields with JAVA

I work at a printing company that has many programs in COBOL and I have been tasked to
convert the COBOL programs into JAVA programs. I've run into a snag in the one conversion. I need to take a file that each line is a record and on each line the data is blocked.
Example of a line is
60000003448595072410013 FFFFFFFFFFV 80 0001438001000014530020120808060134
I need to sort data by a 5 digit number at the 19-23 characters and then by the very first character on a line.
BufferedReader input;
BufferedWriter output;
String[] sort, sorted, style, accountNumber, customerNumber;
String holder;
int lineCount;
int lineCounter() {
int result = 0;
boolean eof = false;
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
while (!eof) {
holder = input.readLine();
if (holder == null) {
eof = true;
} else {
result++;
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
return result;
}
chemSort(){
lineCount = this.lineCounter();
sort = new String[lineCount];
sorted = new String[lineCount];
style = new String[lineCount];
accountNumber = new String[lineCount];
customerNumber = new String[lineCount];
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
for (int i = 0; i < (lineCount + 1); i++) {
holder = input.readLine();
if (holder != null) {
sort[i] = holder;
style[i] = sort[i].substring(0, 1);
customerNumber[i] = sort[i].substring(252, 257);
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}
This what I have so far and I'm not really sure where to go from here or even if this is the correct way
to go about sorting the file. After the file is sorted it will be stored into another file and processed
again with another program for it to be ready for printing.
List<String> linesAsList = new ArrayList<String>();
String line=null;
while(null!=(line=reader.readLine())) linesAsList.add(line);
Collections.sort(linesAsList, new Comparator<String>() {
public int compare(String o1,String o2){
return (o1.substring(18,23)+o1.substring(0,1)).compareTo(o2.substring(18,23)+o2.substring(0,1));
}});
for (String line:linesAsList) System.out.println(line); // or whatever output stream you want
This phone's autocorrect is messing up my answer
Read the file into an ArrayList (instead of an array). Use the following methods:
// to declare the arraylist
ArrayList<String> lines = new ArrayList<String>();
// to add a new line to it (within your reading-lines loop)
lines.add(input.readLine());
Then, sort it using a custom Comparator:
Collections.sort(lines, new Comparator<String>() {
public int compare(String a, String b) {
String a5 = theFiveNumbersOf(a);
String b5 = theFiveNumbersOf(b);
int firstComparison = a5.compareTo(b5);
if (firstComparison != 0) { return firstComparison; }
String a1 = theDigitOf(a);
String b1 = theDigitOf(b);
return a1.compareTo(b1);
}
});
(It is unclear what 5 digits or what digit you want to compare; I've left them as functions for you to fill in).
Finally, write it to the output file:
BufferedWriter ow = new BufferedWriter(new FileOutputStream("filename.extension"));
for (String line : lines) {
ow.println(line);
}
ow.close();
(adding imports and try/catch as needed)
This code will sort a file based on mainframe sort parameters.
You pass 3 parameters to the main method of the Sort class.
The input file path.
The output file path.
The sort parameters in mainframe sort format. In your case, this string would be 19,5,CH,A,1,1,CH,A
This first class, the SortParameter class, holds instances of the sort parameters. There's one instance for every group of 4 parameters in the sort parameters string. This class is a basic getter / setter class, except for the getDifference method. The getDifference method brings some of the sort comparator code into the SortParameter class to simplify the comparator code in the Sort class.
public class SortParameter {
protected int fieldStartByte;
protected int fieldLength;
protected String fieldType;
protected String sortDirection;
public SortParameter(int fieldStartByte, int fieldLength, String fieldType,
String sortDirection) {
this.fieldStartByte = fieldStartByte;
this.fieldLength = fieldLength;
this.fieldType = fieldType;
this.sortDirection = sortDirection;
}
public int getFieldStartPosition() {
return fieldStartByte - 1;
}
public int getFieldEndPosition() {
return getFieldStartPosition() + fieldLength;
}
public String getFieldType() {
return fieldType;
}
public String getSortDirection() {
return sortDirection;
}
public int getDifference(String a, String b) {
int difference = 0;
if (getFieldType().equals("CH")) {
String as = a.substring(getFieldStartPosition(),
getFieldEndPosition());
String bs = b.substring(getFieldStartPosition(),
getFieldEndPosition());
difference = as.compareTo(bs);
if (getSortDirection().equals("D")) {
difference = -difference;
}
}
return difference;
}
}
The Sort class contains the code to read the input file, sort the input file, and write the output file. This class could probably use some more error checking.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sort implements Runnable {
protected List<String> lines;
protected String inputFilePath;
protected String outputFilePath;
protected String sortParameters;
public Sort(String inputFilePath, String outputFilePath,
String sortParameters) {
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.sortParameters = sortParameters;
}
#Override
public void run() {
List<SortParameter> parameters = parseParameters(sortParameters);
lines = read(inputFilePath);
lines = sort(lines, parameters);
write(outputFilePath, lines);
}
protected List<SortParameter> parseParameters(String sortParameters) {
List<SortParameter> parameters = new ArrayList<SortParameter>();
String[] field = sortParameters.split(",");
for (int i = 0; i < field.length; i += 4) {
SortParameter parameter = new SortParameter(
Integer.parseInt(field[i]), Integer.parseInt(field[i + 1]),
field[i + 2], field[i + 3]);
parameters.add(parameter);
}
return parameters;
}
protected List<String> sort(List<String> lines,
final List<SortParameter> parameters) {
Collections.sort(lines, new Comparator<String>() {
#Override
public int compare(String a, String b) {
for (SortParameter parameter : parameters) {
int difference = parameter.getDifference(a, b);
if (difference != 0) {
return difference;
}
}
return 0;
}
});
return lines;
}
protected List<String> read(String filePath) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return lines;
}
protected void write(String filePath, List<String> lines) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filePath));
for (String line : lines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.err.println("The sort process requires 3 parameters.");
System.err.println(" 1. The input file path.");
System.err.println(" 2. The output file path.");
System.err.print (" 3. The sort parameters in mainframe ");
System.err.println("sort format. Example: 15,5,CH,A");
} else {
new Sort(args[0], args[1], args[2]).run();
}
}
}

Read text line and put in to the JTable

hey
i have text file shown as below.
11/2/2010 cat 6
11/2/2010 cat 3
11/2/2010 dog 4
11/2/2010 cat 11
11/3/2010 cat 1
11/3/2010 dog 3
11/3/2010 cat 8
i have in every month this kind of text file. Above figure shows the part of the text file. so then i want to read this text using java to Jtable.
i Have used StringTokanizer And Arreaylist to ceate this. Unfotunately i couldn't done it. SO PLS HELP ME........
So i want below result to jTable using java program.
date animal total count
11/2/2010 cat 20 3
11/3/2010 cat 9 2
You don't need a StringTokenizer (in fact, it's not recommended). Just get the input line by line using BufferedReader, and do a String split:
List<Array> data = new ArrayList<Array>();
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
// Read input and put into ArrayList of Arrays
while ((line = in.readLine) != null) {
data.add(line.split("\\s+"));
}
// Now create JTable with Array of Arrays
JTable table = new JTable(data.toArray(), new String[] {
"date", "animal", "total", "count"});
test with : http://crysol.org/es/node/819
or
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class Reader {
public Reader() {
// TODO Auto-generated constructor stub
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt")));
Map<String, Object[]> result = new LinkedHashMap<String, Object[]>();
while (reader.ready()) {
String line = reader.readLine();
String[] values = line.split("\\s+");
String key = values[0] + "\t" + values[1];
String label = values[0];
String date = values[1];
Integer sum = 0;
Integer count = 0;
if (result.containsKey(key)) {
sum = (Integer) ((Object[]) result.get(key))[2];
count = (Integer) ((Object[]) result.get(key))[3];
} else {
}
result.put(key, new Object[]{label, date,
sum + Integer.parseInt(values[2]), count + 1});
}
ArrayList arrayList = new ArrayList(result.values());
/* interate and print new output */
/*
* for (String key : result.keySet()) { Integer sum =
* result.get(key); Integer count = result2.get(key);
* System.out.println(key + " " + sum + "\t" + count); }
*/
JTable table = new JTable(new AnimalTableModel(arrayList));
panel.add(new JScrollPane(table));
reader.close();
frame.setContentPane(panel);
frame.setVisible(true);
frame.pack();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Reader();
}
public class AnimalTableModel implements TableModel {
final Class[] columnClass = new Class[]{String.class, String.class,
Integer.class, Integer.class};
final String[] columnName = new String[]{"Date", "Animal", "Sum",
"Count"};
List values = null;
public AnimalTableModel(List values) {
this.values = values;
// initilize values
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return columnClass[columnIndex];
}
#Override
public int getColumnCount() {
return columnClass.length;
}
#Override
public String getColumnName(int columnIndex) {
return columnName[columnIndex];
}
#Override
public int getRowCount() {
return values.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ((Object[]) values.get(rowIndex))[columnIndex];
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// TODO FOR EDITABLE DT
}
}
}
You will have to populate the data to a map from the given file.I will give you an example as to how to populate the data.
public class AnimalMapping {
public static void main(String[] args) {
Object[][] data = { { "11/2/2010", "cat", 6 },
{ "11/2/2010", "cat", 3 }, { "11/2/2010", "dog", 4 },
{ "11/2/2010", "cat", 11 }, { "11/3/2010", "cat", 1 },
{ "11/3/2010", "dog", 3 }, { "11/3/2010", "cat", 8 } };
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
for (Object[] record : data) {
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put((String) record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put((String) record[1], obj);
}
obj.Sumval += (Integer) record[2];
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
Once you have got the data in a map then it's easy to populate these data to a table.You can use a tablemodel for this purpose.Have a look at this code to understand how data from a map can be loaded into a table using TableModel.
UPDATE:
public class AnimalMapping {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
String[] record;
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
while(((line = in.readLine()) != null)) {
record=line.split("\\s+");
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put(record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put(record[1], obj);
}
obj.Sumval += Integer.valueOf(record[2]);
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
#Dilantha Chamal: Reading from file was already given by Box9.I just included it in my code.You should be putting some effort here.Maybe you are a beginner that's why I wrote the code.Now try to implement the TableModel by yourself.Just a friendly advice:unless you do it you are never going to learn.
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class AnimalSummaryBuilder
{
private static final Splitter SPLITTER = Splitter.on(CharMatcher.anyOf(","));
private static final Joiner JOINER = Joiner.on("\t");
#SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception
{
#SuppressWarnings("rawtypes")
Map<Animal, Summary> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {
private final Map<Animal, Summary> result = Maps.newHashMap();
public Object getResult()
{
return result;
}
public boolean processLine(final String line) throws IOException
{
Iterator<String> columns = SPLITTER.split(line).iterator();
String date = columns.next();
String name = columns.next();
int value = Integer.valueOf(columns.next()).intValue();
Animal currentRow = new Animal(date, name);
if (result.containsKey(currentRow))
{
Summary summary = result.get(currentRow);
summary.increaseCount();
summary.addToTotal(value);
}
else
{
Summary initialSummary = new Summary();
initialSummary.setCount(1);
initialSummary.setTotal(value);
result.put(currentRow, initialSummary);
}
return true;
}
});
for (Map.Entry<Animal, Summary> entry : result.entrySet())
{
Animal animal = entry.getKey();
Summary summary = entry.getValue();
System.out.println(JOINER.join(animal.date, animal.name, summary.total, summary.count));
}
}
final static class Animal
{
String date;
String name;
public Animal(final String date, final String n)
{
this.date = date;
this.name = n;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Animal))
{
return false;
}
Animal other = (Animal) obj;
if (date == null)
{
if (other.date != null)
{
return false;
}
}
else if (!date.equals(other.date))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
}
final static class Summary
{
private int total;
private int count;
void setTotal(int value)
{
total = value;
}
void setCount(int i)
{
count = i;
}
void increaseCount()
{
count++;
}
void addToTotal(int valueToAdd)
{
total += valueToAdd;
}
}
}

Categories

Resources