JavaAdding List to TreeMap and Display out key and list - java

I have the following textfile contains the information that will be added to the treemap.
1 apple
1 orange
3 pear
3 pineapple
4 dragonfruit
my code:
public class Treemap {
private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
public static void main(String[] args) {
Treemap tm = new Treemap();
String file = "";
if (args.length == 1) {
file = args[0];
try {
tm.Read(file);
} catch (IOException ex) {
System.out.println("Error");
}
} else {
System.out.println("Usage: java treemap 'Filename'");
System.exit(1);
}
}
public void Read(String file) throws IOException {
//Scanner in = null;
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
if (file_Array[0].equalsIgnoreCase("1")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(1);
} else if (file_Array[0].equalsIgnoreCase("3")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(3);
} else if (file_Array[0].equalsIgnoreCase("4")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
Display(4);
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item) == false) {
tMap.put(item, fList);
fList.add(fruit);
System.out.println("Fruits added " + item);
} else {
System.out.println("not exist");
}
}
public void Display(int item) {
if (tMap.containsKey(item)) {
System.out.print("Number " + item + ":" + "\n");
System.out.print(fList);
System.out.print("\n");
} else {
System.out.print(item + " WAS NOT FOUND"+ "\n");
}
}
}
ideal output
Number 1:
[apple, orange]
Number 3:
[pear, pineapple]
Number 4:
[dragonfruit]
currently i only able to output this
Fruits added 1
Number 1:
[apple]
not exist
Number 1:
[apple]
Fruits added 3
Number 3:
[apple, pear]
not exist
Number 3:
[apple, pear]
Fruits added 4
Number 4:
[apple, pear, dragonfruit]
How should I display the item following by the list of fruit added to that number?

Try this code. Its working. By the way you should improve this code. The code is not optimised.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class Treemap {
private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();
public static void main(String[] args) {
Treemap tm = new Treemap();
String file = "";
if (args.length == 1) {
file = args[0];
try {
tm.Read(file);
} catch (IOException ex) {
System.out.println("Error");
}
} else {
System.out.println("Usage: java treemap 'Filename'");
System.exit(1);
}
}
public void Read(String file) throws IOException {
//Scanner in = null;
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
if (file_Array[0].equalsIgnoreCase("1")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(1);
} else if (file_Array[0].equalsIgnoreCase("3")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(3);
} else if (file_Array[0].equalsIgnoreCase("4")) {
Add(Integer.parseInt(file_Array[0]), file_Array[1]);
// Display(4);
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
for(int i: tMap.keySet())
Display(i);
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item) == false) {
fList = new ArrayList<>();
fList.add(fruit);
tMap.put(item, fList);
// System.out.println("Fruits added " + item);
} else {
tMap.get(item).add(fruit);
// System.out.println("not exist");
}
}
public void Display(int item) {
if (tMap.containsKey(item)) {
System.out.print("Number " + item + ":" + "\n");
System.out.print(tMap.get(item));
System.out.print("\n");
} else {
System.out.print(item + " WAS NOT FOUND"+ "\n");
}
}
}

Here is your READ , ADD ad DISPLAY method,
public void Read(String file) throws IOException {
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" ", 2);
Add(Integer.parseInt(file_Array[0]),file_Array[1]);
}
Display(-1); // -1 for displaying all
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
System.exit(1);
} finally {
in.close();
}
}
public void Add(int item, String fruit) {
if (tMap.containsKey(item)) {
fList = tMap.get(item);
} else {
fList = new ArrayList<String>();
}
fList.add(fruit);
tMap.put(item, fList);
}
public void Display(int key) {
if(key == -1){
for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}else{
System.out.println(key);
System.out.println(tMap.get(key));
}
}

You make unnecessary complicated your code. Try with simple code.
public class Treemap {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("file.txt"));
Map<Integer, List<String>> tMap = new TreeMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] values=line.split(" ");
List<String> fList;
Integer key=Integer.valueOf(values[0]);
if(tMap.containsKey(key)){//Key already inserted
fList=tMap.get(key); //Get existing List of key
fList.add(values[1]);
}
else{
fList = new ArrayList<String>();
fList.add(values[1]);
tMap.put(key, fList);
}
}
for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
Output:
1
[apple, orange]
3
[pear, pineapple]
4
[dragonfruit]

Change some code for the method Add(), which is incorrect in your code.
What if the Map contains the key?
Following code is modified based on your code, hope this can help you some.
public void Add(int item, String fruit) {
if (tMap.containsKey(item)==false) {
fList.clear();
fList.add(fruit);
tMap.put(item, fList);
System.out.println("Fruits added " + item);
} else {
tMap.get(item).add(fruit);
}
}

Related

Java - Collection

I'm working on my first java project and I have a question. The question should be quiet simple (though the the code is not that short, but there's no reason to be intimidated :) ). I create a basic roleplaying-game and I have an abstract class "Character" that defines each character. Among its subclasses you can find Mage, who has a Spellbook (Map). Spellbook class offers methods like addToSpellbook, that works fine. In addition I have an Inventory class that has addToInventory method, which is quit identical to addToSpellbook.
My question is as follows - why can I use In the main method addToSpellbook and can't use AddToInventory?
I guess the reason is that Map doesn't have AddToInventory, so I should override put, but still, how can I use addToSpellbook ?
public class Game {
public static void main(String[] args) throws IOException {
CharacterCreator heroCreator = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
String chosenClass = CharacterCreator.getCharacterClass(scan);
Character hero = CharacterCreator.createCharacter(chosenClass);
try {
hero.displayCharacter();
}catch (Exception e){
System.out.println("Problem displaying character data");
}
hero.getInventory().addToInventory("Long sword");
CharacterCreator heroCreator2 = new CharacterCreator();
CharacterCreator.showAllClasses();
Scanner sc2 = new Scanner(System.in);
int scan2 = sc.nextInt();
String chosenClass2 = CharacterCreator.getCharacterClass(scan2);
Character hero2 = CharacterCreator.createCharacter(chosenClass2);
try {
hero2.displayCharacter();
}catch (Exception e){
System.out.println("Wrong input");
}
if(hero instanceof Mage) {
((Mage)hero).getSpellBook().addToSpellBook("Magic Missiles");
((Mage)hero).getSpellBook().addToSpellBook("Fireball");
((Mage)hero).getSpellBook().addToSpellBook("Mage Armor");
((Mage)hero).getSpellBook().showSpellBook();
((Mage)hero).getSpellBook().getSpellFromSpellbook("Fireball").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Magic Missiles").castSpell(hero, hero2);
((Mage)hero).getSpellBook().getSpellFromSpellbook("Mage Armor").castSpell(hero, hero);
}
}
}
abstract public class Character {
private Equipment equipment;
private Map<String, Integer> inventory;
protected Character(String name){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
protected Character(String name, int lvl){
equipment = new Equipment();
inventory = new HashMap<String, Integer>();
}
}
public Equipment getEquipment() { return equipment; }
public Map getInventory() { return inventory; }
}
public class Inventory {
private Map<String,Integer> inventory;
Inventory() {
inventory = new HashMap<String, Integer>();
}
public void addToInventory(String item) {
boolean found = false;
try {
for (Iterator<Map.Entry<String, Integer>> iter = inventory.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Integer> newItem = iter.next();
if (newItem.getKey() == item) {
inventory.put(item, inventory.get(newItem) + 1);
break;
}
}
}catch (Exception e) {
System.out.println(item + " : adding failed");
}
if (!found) {
inventory.put(item,1);
}
}
public void showInventory() {
System.out.println("Show Inventory: ");
for (Map.Entry<String,Integer> entry: inventory.entrySet()) {
System.out.println( entry.getKey() + ", quantity: " + entry.getValue() );
}
System.out.println("");
}
}
public class Mage extends Character {
private SpellBook spellBook;
public Mage(String name) {
super(name);
SpellBook spellbook = new SpellBook();
}
protected Mage(String name, int lvl){
super(name, lvl);
spellBook = new SpellBook();
}
public SpellBook getSpellBook() { return spellBook; }
}
}
public class SpellBook {
private Map<String, Spell> spellBook;
SpellBook() {
spellBook = new HashMap<String, Spell>();
}
public Map getSpellBook() { return spellBook; }
public void addToSpellBook(String spellName) {
Spell newSpell = null;
try {
if (DamageSpell.getSpell(spellName) != null) {
newSpell = DamageSpell.getSpell(spellName);
} else if (ChangeStatSpell.getSpell(spellName) != null) {
newSpell = ChangeStatSpell.getSpell(spellName);
}
System.out.println(newSpell.getSpellName() + " has been added to the spellbook");
spellBook.put(newSpell.getSpellName(), newSpell);
} catch (Exception e){
System.out.println("Adding " + spellName +"to spellbook has failed");
}
}
public void showSpellBook() {
System.out.println("Show spellbook: ");
for (Iterator<String> iter = spellBook.keySet().iterator(); iter.hasNext(); ) {
String spell = iter.next();
System.out.println(spell);
}
System.out.println("");
}
public Spell getSpellFromSpellbook(String spellName) {
Spell spl = null;
//Spell splGet = spellBook.get(spellName); /* straight forward implementation*/
// System.out.println("The spell " + splGet.getSpellName() + " has been retrived from the spellbook by using get method");
try {
for (Iterator<Map.Entry<String, Spell>> iter = spellBook.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, Spell> spell = iter.next();
if (spell.getKey() == spellName) {
spl = spell.getValue();
}
}
}catch (Exception e) {
System.out.println(spellName + " : no such spell in spellbook");
}
return spl;
}
}
getInventory() returns a Map and Map doesn't have the addToInventory() method.
getInventory() should add an Inventory instance.

How to import the text file and put it in HashMap? we need to give code for each company to get details about that company later

public class Companydatabase {
public static void main(String[] args) {
Companydatabase obj = new Companydatabase();
obj.run();
}
public void run() {
String File = "nishan.txt";
BufferedReader br = null;
String line = "";
String split = ",";
try {
Map<String, String> maps = new HashMap<String, String>();
I could not add each file string to HashMap. i wish some one could help me.
br = new BufferedReader(new FileReader(File));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(split);
maps.put(country[0], country[1], country[2], country[3]);
}
//loop map
for (Map.Entry<String, String> entry : maps.entrySet()) {
System.out.println("Country [code= " + entry.getKey() + " , name="
+ entry.getValue() + "]");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}

OrientDB slow when browsing cluster

Well what i am trying to achieve is to save pairs of words in a sentence and if the word is already there , i am trying to save a list of words against one.
To save the pairing as there could many millions as my data set file is very large , i opted for orientdb. I dont know if i am approaching it correctly but orientdb is very slow. After 8 hours of running it has only made pairs for 12000 sentences.
As far as i have checked the major slowdown was in browsing cluster.
Attached is my code, please if ant one can give any pointers over my approach.
public static void main(String[] args) {
// TODO Auto-generated method stub
Main m = new Main();
m.openDatabase();
m.readFile("train_v2.txt");
m.closeDatabase();
}
}
class Main {
ODatabaseDocumentTx db;
Map<String, Object> index;
List<Object> list = null;
String pairing[];
ODocument doc;
Main() {
}
public void closeDatabase() {
if (!db.isClosed()) {
db.close();
}
}
void openDatabase() {
db = new ODatabaseDocumentTx("local:/databases/model").open("admin",
"admin");
doc = new ODocument("final");
}
public void readFile(String filename) {
InputStream ins = null; // raw byte-stream
Reader r = null; // cooked reader
int i = 1;
BufferedReader br = null; // buffered for readLine()
try {
String s;
ins = new FileInputStream(filename);
r = new InputStreamReader(ins, "UTF-8"); // leave charset out
// for
// default
br = new BufferedReader(r);
while ((s = br.readLine()) != null) {
System.out.println("" + i);
createTermPair(s.replaceAll("[^\\w ]", "").trim());
i++;
}
} catch (Exception e) {
System.err.println(e.getMessage()); // handle exception
} finally {
closeDatabase();
if (br != null) {
try {
br.close();
} catch (Throwable t) { /* ensure close happens */
}
}
if (r != null) {
try {
r.close();
} catch (Throwable t) { /* ensure close happens */
}
}
if (ins != null) {
try {
ins.close();
} catch (Throwable t) { /* ensure close happens */
}
}
}
}
private void createTermPair(String phrase) {
phrase = phrase + " .";
String[] word = phrase.split(" ");
for (int i = 0; i < word.length - 1; i++) {
if (!word[i].trim().equalsIgnoreCase("")
&& !word[i + 1].trim().equalsIgnoreCase("")) {
String wordFirst = word[i].toLowerCase().trim();
String wordSecond = word[i + 1].toLowerCase().trim();
String pair = wordFirst + " " + wordSecond;
checkForPairAndWrite(pair);
}
}
}
private void checkForPairAndWrite(String pair) {
try {
pairing = pair.trim().split(" ");
if (!pairing[1].equalsIgnoreCase(" ")) {
index = new HashMap<String, Object>();
for (ODocument docr : db.browseCluster("final")) {
list = docr.field(pairing[0]);
}
if (list == null) {
list = new ArrayList<>();
}
list.add("" + pairing[1]);
if (list.size() >= 1)
index.put(pairing[0], list);
doc.fields(index);
doc.save();
}// for (int i = 0; i < list.size(); i++) {
// System.out.println("" + list.get(i));
// }
} catch (Exception e) {
}
return;
}
}

fill arrayList with dat file

Here's the code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib
{
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib()
{
loadNouns();
loadVerbs();
loadAdjectives();
out.println(nouns);
}
public MadLib(String fileName)
{
//load stuff
loadNouns();
loadVerbs();
loadAdjectives();
try{
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e)
{
out.println("Houston we have a problem!");
}
}
public void loadNouns()
{
nouns = new ArrayList<String>();
try{
//nouns = new ArrayList<String>();
String nou = "";
Scanner chopper = new Scanner(new File ("nouns.dat"));
//chopper.nextLine();
while(chopper.hasNext()){
nou = chopper.next();
out.println(nou);
nouns.add(nou);
//chopper.nextLine();
}
//chopper.close();
out.println(nouns.size());
}
catch(Exception e)
{
out.println("Will");
}
}
public void loadVerbs()
{
verbs = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("verbs.dat"));
while(chopper.hasNext()){
verbs.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
out.println("run");
}
}
public void loadAdjectives()
{
adjectives = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("adjectives.dat"));
while(chopper.hasNext()){
adjectives.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
}
}
public String getRandomVerb()
{
String verb = "";
int num = 0;
num = (int)(Math.random()*(verbs.size()-1));
verb = verbs.get(num);
return verb;
}
public String getRandomNoun()
{
String noun = "";
int num = 0;
if(nouns == null){
loadNouns();
}
double rand = (Math.random());
num = (int)(rand * (nouns.size()-1));
out.println(num);
noun = nouns.get((int) num);
out.print(noun);
return noun;
}
public String getRandomAdjective()
{
String adj = "";
int num = 0;
num = (int)(Math.random()*(adjectives.size()-1));
adj = adjectives.get(num);
return adj;
}
public String toString()
{
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
and here's one of the .dat files (the other 2 are the exact same aside from the specific words they contain):
dog
pig
chicken
building
car
person
place
thing
truck
city
state
school
student
bird
turkey
lion
tiger
alligator
elephant
My issue is that I can't get any of my arrayLists to read in their appropriate .dat files and from my POV, my code seems like it should do that
UPDATE
current output aside from the absence of "Will" (I removed that line):
run
[ ]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MadLib.getRandomNoun(MadLib.java:130)
at MadLib.toString(MadLib.java:147)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at Lab16d.main(Lab16d.java:18)
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public static void main(String args[]) {
MadLib a = new MadLib();
System.out.println(a.toString());
}
public MadLib() {
loadAllWords();
System.out.println(nouns);
}
public MadLib(String fileName) {
loadAllWords();
try {
Scanner file = new Scanner(new File(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadAllWords() {
loadNouns();
loadVerbs();
loadAdjectives();
}
public void loadNouns() {
nouns = loadFile("nouns.dat");
}
public void loadVerbs() {
verbs = loadFile("verbs.dat");
}
public void loadAdjectives() {
adjectives = loadFile("adjectives.dat");
}
public ArrayList<String> loadFile(String filename) {
ArrayList<String> words = new ArrayList<String>();
try {
Scanner chopper = new Scanner(new File(filename));
while (chopper.hasNext()) {
words.add(chopper.next());
// just calling nextLine will cause an exception at the end of the file unless you have an blank line there on purpose, so this makes sure it does
if (chopper.hasNext()) {
chopper.nextLine();
}
}
chopper.close();
} catch (Exception e) {
e.printStackTrace();
}
return words;
}
public String getRandomWord(ArrayList<String> words) {
Random rand = new Random();
int num = rand.nextInt(words.size());
String word = nouns.get(num);
System.out.println(word);
return word;
}
public String getRandomVerb() {
if (verbs == null) {
loadNouns();
}
return getRandomWord(verbs);
}
public String getRandomNoun() {
if (nouns == null) {
loadNouns();
}
return getRandomWord(nouns);
}
public String getRandomAdjective() {
if (adjectives == null) {
loadNouns();
}
return getRandomWord(adjectives);
}
public String toString() {
return "The " + getRandomNoun() + " " + getRandomVerb() + " after the " + getRandomAdjective() + " " + getRandomAdjective() + " " + getRandomNoun() + " while the " + getRandomNoun() + " " + getRandomVerb() + " the " + getRandomNoun();
}
}

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();
}
}
}

Categories

Resources