I am loading text file contents to GUI and counting HashMap values using this code:
Map<String, ArrayList<String>> sections = new HashMap<>();
Map<String, String> sections2 = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 50).trim();
if (k.equals(""))
k = lastKey;
ArrayList<String> authors = null;
if(sections.containsKey(k))
{
authors = sections.get(k);
}
else
{
authors = new ArrayList<String>();
sections.put(k, authors);
}
authors.add(v);
lastKey = k;
}
} catch (IOException e) {
}
// to get the number of authors
int numOfAuthors = sections.get("AUTHOR").size();
// to count HashMap value
jButton1.addActionListener(new Clicker(numOfAuthors));
jButton1.doClick();
// convert the list to a string to load it in a GUI
String authors = "";
for (String a : sections.get("AUTHOR"))
{
authors += a;
}
jcb1.setSelectedItem(authors);
The ActionListener of jButton1 was borrowed from here.
Now I want to assign AUTHOR (the number of items in HashMap is 12, so jButton1 will add dynamic 12 jComboBoxes) values to dynamically created jComboBoxes.
I have tried this code:
BufferedReader br = new BufferedReader(new FileReader ("input.txt"));
String str=null;
int i = 0;
while( (str = br.readLine()) !=null ) {
String v = str.substring(12, str.length() - 61).trim();
if(i == 0) {
jcb1.setSelectedItem(v);
} else {
SubPanel panel = (SubPanel) jPanel2.getComponent(i - 1);
JComboBox jcb = panel.getJcb();
jcb.setSelectedItem(v);
}
i++;
}
But this code read from input.txt all lines (70 lines), but I want to assign just that 12 values from AUTHOR field and show them on jcb.
How can I solve it?
You shouldn't have to re-read the entire text file again in order to complete the setup of the GUI. I would just read the text file once, then use the Map<String, ArrayList<String>> sections = new HashMap<>(); object to complete the setup of the GUI.
This could be the process for you:
1) Read the entire file and return the sections HashMap.
2) Setup the jPanel2 by adding the SubPanels to it (e.g. based on the number of Authors).
3) Setup the JComboBox's by adding the data stored in the HashMap (e.g. the mapped ArrayList's).
For number 1), I would just create a method that reads the file and returns the HashMap.
Read The File
Example (Adapted from your other question here):
public Map<String, ArrayList<String>> getSections ()
{
Map<String, ArrayList<String>> sections = new HashMap<>();
String s = "", lastKey = "";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt")))
{
while ((s = br.readLine()) != null)
{
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 50).trim();
if (k.equals(""))
k = lastKey;
ArrayList<String> authors = null;
if (sections.containsKey(k))
{
authors = sections.get(k);
}
else
{
authors = new ArrayList<String>();
sections.put(k, authors);
}
// don't add empty strings
if (v.length() > 0)
{
authors.add(v);
}
lastKey = k;
}
}
catch (IOException e)
{
e.printStackTrace();
}
return sections;
}
GUI Setup
Note: This code can be put wherever you are setting up the GUI now, I'm just placing all in the method below for an example.
public void setupGUI ()
{
// read the file and get the map
Map<String, ArrayList<String>> sections = getSections();
// get the authors
ArrayList<String> authors = sections.get("AUTHOR");
// Setup the jPanel2 by adding the SubPanels
int num = authors.size();
jButton1.addActionListener(new Clicker(num));
jButton1.doClick();
// Setup the JComboBox's by adding the data stored in the map
for (int i = 0; i < authors.size(); i++)
{
int index = i;
// not sure if getComponent() is zero or 1-baed so adjust the index accordingly.
SubPanel panel = (SubPanel) jPanel2.getComponent(index);
// Not sure if you already have the JComboBox in the SubPanel
// If not, you can add them here.
JComboBox jcb = panel.getJcb();
jcb.setSelectedItem(authors.get(i));
}
}
Side Note: I'm not sure why you are creating 12 separate SubPanel's, each with its own JComboBox? Maybe you want to consider how you can better layout the GUI. Just a consideration. In either case, you can use the above examples are a starting point.
Related
Using the code from this link loading text file contents to GUI:
Map<String, String> sections = new HashMap<>();
Map<String, String> sections2 = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 50).trim();
if (k.equals(""))
k = lastKey;
if(sections.containsKey(k))
v = sections.get(k) + v;
sections.put(k,v);
lastKey = k;
}
} catch (IOException e) {
}
System.out.println(sections.get("AUTHOR"));
System.out.println(sections2.get("TITLE"));
In case of if contents of input.txt:
AUTHOR authors name
authors name
authors name
authors name
TITLE Sound, mobility and landscapes of exhibition: radio-guided
tours at the Science Museum
Now I want to count the values in HashMap, but sections.size() counting all data line stored in text file.
I w'd like to ask how can I count the items, i.e. values v in sections? How can I get number 4, according to authors name?
Since the AUTHOR has a 1 to many relationship, you should map it to a List structure instead of a String.
For example:
Map<String, ArrayList<String>> sections = new HashMap<>();
Map<String, String> sections2 = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 50).trim();
if (k.equals(""))
k = lastKey;
ArrayList<String> authors = null;
if(sections.containsKey(k))
{
authors = sections.get(k);
}
else
{
authors = new ArrayList<String>();
sections.put(k, authors);
}
authors.add(v);
lastKey = k;
}
} catch (IOException e) {
}
// to get the number of authors
int numOfAuthors = sections.get("AUTHOR").size();
// convert the list to a string to load it in a GUI
String authors = "";
for (String a : sections.get("AUTHOR"))
{
authors += a;
}
I have a data like :
in an arraylist of Strings I am collecting names .
example:
souring.add(some word);
later I have something in souring = {a,b,c,d,d,e,e,e,f}
I want to assign each element a key like:
0=a
1=b
2=c
3=d
3=d
4=e
4=e
4=e
5=f
and then I store all ordering keys in an array . like:
array= [0,1,2,3,3,4,4,4,5]
heres my code on which I am working :
public void parseFile(String path){
String myData="";
try {
BufferedReader br = new BufferedReader(new FileReader(path)); {
int remainingLines = 0;
String stringYouAreLookingFor = "";
for(String line1; (line1 = br.readLine()) != null; ) {
myData = myData + line1;
if (line1.contains("relation ") && line1.endsWith(";")) {
remainingLines = 4;//<Number of Lines you want to read after keyword>;
stringYouAreLookingFor += line1;
String everyThingInsideParentheses = stringYouAreLookingFor.replaceFirst(".*\\((.*?)\\).*", "$1");
String[] splitItems = everyThingInsideParentheses.split("\\s*,\\s*");
String[] sourceNode = new String[10];
String[] destNode = new String[15];
int i=0;
int size = splitItems.length;
int no_of_sd=size;
tv.setText(tv.getText()+"size " + size + "\n"+"\n"+"\n");
sourceNode[0]=splitItems[i];
// here I want to check and assign keys and track order...
souring.add(names);
if(size==2){
destNode[0]=splitItems[i+1];
tv.setText(tv.getText()+"dest node = " + destNode[0] +"\n"+"\n"+"\n");
destination.add(destNode[0]);
}
else{
tv.setText(tv.getText()+"dest node = No destination found"+"\n"+"\n"+"\n");
}
} else if (remainingLines > 0) {
remainingLines--;
stringYouAreLookingFor += line1;
}
}
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
How can I do this?
can any one help me in this..?
I would advise you to use ArrayList instead of String[]
So, if you want to add an element you just write
ArrayList<String> list = new ArrayList<String>;
list.add("whatever you want");
Then, if you want to avoid repetitions just use the following concept:
if(!list.contains(someString)){
list.add(someString);
}
And if you want to reach some element you just type:
list.get(index);
Or you can easily find an index of an element
int index=list.indexOf(someString);
Hope it helps!
Why don't you give it a try, its take time to understand what you actually want.
HashMap<Integer,String> storeValueWithKey=new HashMap<>();
// let x=4 be same key and y="x" be new value you want to insert
if(storeValueWithKey.containsKey(x))
storeValueWithKey.get(x)+=","+y;
else
storeValueWithKey.put(z,y); //Here z is new key
//Than for searching ,let key=4 be value and searchValue="a"
ArrayList<String> searchIn=new ArrayList<>(Arrays.asList(storeValueWithKey.get("key").split(",")));
if(searchIn.contains("searchValue"))
If problem still persist than comment
I want to retrieve some rows of a 2d array.
example: I have file named as "data.csv", which contains
age sex zipcode classtype
21 m 23423 1
12 f 23133 2
23 m 32323 2
23 f 23211 1
The below mentioned code will give output like this:
{age=[21,12,23,23],sex=[m,f,m,f],zipcode=[23423,23133,32323,23211],classtype=[1,2,2,1]}
Now I want to retrieve rows which have classtype 1 and store this values in a new 2d array.
like partition1={{21,m,23423,1},{23,f,23211,1}}
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, " ", true);
System.out.println(values);
List<List<String>> partition1 = new ArrayList<>(25);
List<String> classTypes = values.get("classtype");
for (int row = 0; row < classTypes.size(); row++) {
String classType = classTypes.get(row);
if ("1".equals(classType)) {
List<String> data = new ArrayList<>(25);
data.add(values.get("age").get(row));
data.add(values.get("sex").get(row));
data.add(values.get("zipcode").get(row));
data.add(values.get("classtype").get(row));
partition1.add(data);
}
}
System.out.println(partition1);
} 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;
}
}
FileReader file1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(file1);
String line = "";
while ((line = buffer.readLine()) != null) {
StringBuilder sb = new StringBuilder();
String[] str = line.split(",");
if(str[0]!=null||str[1]!=null||str[2]!=null){
sb.append("'" + str[0] + "',");
sb.append("'" +str[1] + "',");
sb.append("'" +str[2] + "'");
}
CSV File Must to be split comma based it should be work
Once I changed Map<String, List<String>> values = parseCsv(fr, "\\s,", true); to Map<String, List<String>> values = parseCsv(fr, " ", true); I was able to get the data in the right format...
From there it was just a matter to read through each row of classtype, when I found a value that matched 1, I would pull out each property for the given row and add it to a List, forming a single row. This was then added to another List which would maintain all the matching rows, for example...
List<List<String>> partition1 = new ArrayList<>(25);
List<String> classTypes = values.get("classtype");
for (int row = 0; row < classTypes.size(); row++) {
String classType = classTypes.get(row);
if ("1".equals(classType)) {
List<String> data = new ArrayList<>(25);
data.add(values.get("age").get(row));
data.add(values.get("sex").get(row));
data.add(values.get("zipcode").get(row));
data.add(values.get("classtype").get(row));
partition1.add(data);
}
}
System.out.println(partition1);
Which outputs...
[[21, m, 23423, 1], [23, f, 23211, 1]]
If you're looking for a more automated method, then I'm afraid you're out of luck, as Map makes no guarantee about the order that the keys are stored, iterated.
Of course, instead of using a List<List>, you could use a List<Map> which would maintain the keys for each value, for example...
List<Map<String, String>> partition1 = new ArrayList<>(25);
List<String> classTypes = values.get("classtype");
for (int row = 0; row < classTypes.size(); row++) {
String classType = classTypes.get(row);
if ("1".equals(classType)) {
Map<String, String> data = new HashMap<>(25);
for (String key : values.keySet()) {
data.put(key, values.get(key).get(row));
}
partition1.add(data);
}
}
System.out.println(partition1);
Which outputs...
[{sex=m, classtype=1, zipcode=23423, age=21}, {sex=f, classtype=1, zipcode=23211, age=23}]
I want to find the size of each value from the key-value pair in Map<Integer, ArrayList<String>>. Simply writing list.size() does not work.
Here's my code:
public void getF() throws Exception {
BufferedReader br2 =
new BufferedReader(
new FileReader("/home/abc/NetBeansProjects/network1.txt"));
System.out.println("hello" +r.usr);
while ((s= br2.readLine()) != null) {
String F[]= s.split(":");
for (String uid : F) {
if (uid == F[0]) {
user.add(uid);
} else {
li = followee.get(Integer.valueOf(F[0]));
if (li == null) {
followee.put(Integer.valueOf(F[0]), li= new ArrayList<String>());
}
li.add(uid);
}
System.out.println(followee);
int g = li.size();
System.out.println("g:" +g);
[...]
}
}
}
Why am I not getting correct size on last line?
Try to follow the data structures, by keeping the variable as close to their usage.
(I know in other languages the convention is to declare them at the top.)
Here li should be kept at the begin of a while-step. And its more natural to handle f[0] outside the loop, instead of for+if. I think the latter put you on the wrong foot.
Set<String> user = new HashSet<>();
Map<Integer, List<String>> followee = new HashMap<>();
String s;
while ((s = br2.readLine()) != null) {
// s has the format "key:value value value"
String keyAndValues[] = s.split(":", 2);
if (keyAndValues.length != 2) {
continue;
}
Integer key = Integer.valueOf(keyAndValues[0]);
String values = keyAndValues[1];
user.add(keyAndValues[0]);
List<String> li = followee.get(key);
if (li == null) {
li = new ArrayList<>();
followee.put(key, li);
}
Collections.addAll(values.split(" +");
System.out.println(followee);
int g = li.size();
System.out.println("g:" + g);
//[...]
}
I have a directory in which I have 1000 txt.files in it. I want to know for every word how many times it occurs in the 1000 document. So say even the word "cow" occured 100 times in X it will still be counted as one. If it occured in a different document it is incremented by one. So the maximum is 1000 if "cow" appears in every single document. How do I do this the easy way without the use of any other external library. Here's what I have so far
private Hashtable<String, Integer> getAllWordCount()
private Hashtable<String, Integer> getAllWordCount()
{
Hashtable<String, Integer> result = new Hashtable<String, Integer>();
HashSet<String> words = new HashSet<String>();
try {
for (int j = 0; j < fileDirectory.length; j++){
File theDirectory = new File(fileDirectory[j]);
File[] children = theDirectory.listFiles();
for (int i = 0; i < children.length; i++){
Scanner scanner = new Scanner(new FileReader(children[i]));
while (scanner.hasNext()){
String text = scanner.next().replaceAll("[^A-Za-z0-9]", "");
if (words.contains(text) == false){
if (result.get(text) == null)
result.put(text, 1);
else
result.put(text, result.get(text) + 1);
words.add(text);
}
}
}
words.clear();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(result.size());
return result;
}
You also need a HashSet<String> in which you store each unique word you've read from the current file.
Then after every word read, you should check if it's in the set, if it isn't, increment the corresponding value in the result map (or add a new entry if it was empty, like you already do) and add the word to the set.
Don't forget to reset the set when you start to read a new file though.
how about this?
private Hashtable<String, Integer> getAllWordCount()
{
Hashtable<String, Integer> result = new Hashtable<String, Integer>();
HashSet<String> words = new HashSet<String>();
try {
for (int j = 0; j < fileDirectory.length; j++){
File theDirectory = new File(fileDirectory[j]);
File[] children = theDirectory.listFiles();
for (int i = 0; i < children.length; i++){
Scanner scanner = new Scanner(new FileReader(children[i]));
while (scanner.hasNext()){
String text = scanner.next().replaceAll("[^A-Za-z0-9]", "");
words.add(text);
}
for (String word : words) {
Integer count = result.get(word)
if (result.get(word) == null) {
result.put(word, 1);
} else {
result.put(word, result.get(word) + 1);
}
}
words.clear();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(result.size());
return result;
}