How to Create A HashMap using Key Values from a text file? - java

I have to create a hashmap with the names I have in this text file
relationships text file:
Susan Sarandon | Tom Hanks : Cloud Atlas
Tom Hanks | Kevin Bacon : Apollo 13
Leonardo Dicaprio | Kevin Bacon : This Boy's Life
Robert De Niro | Kevin Bacon : This Boy's Life
Barack Obama | Tom Hanks : the Road We've Traveled
Helen Keller | Katharine Cornell : Helen Keller in Her Story
Katharine Cornell | Helen Hayes : Stage Door Canteen
Helen Hayes | John Laughlin : Murder with Mirrors
John Laughlin | Kevin Bacon : Footloose
Mark Zuckerberg | Joe Lipari : Terms and Conditions May Apply
Joe Lipari | Welker White : Eat Pray Love
Welker White | Kevin Bacon : Lemon Sky
This is the program I have now:
public static void main(String[] args)
throws FileNotFoundException
{
Scanner input = new Scanner(new File("relationships"));
HashMap<String, String> relationships = new HashMap<String, String>();
while (input.hasNextLine()) {
String[] columns = input.nextLine().split(" ");
relationships.put(columns[0], columns[1]);
}
System.out.println(relationships);
}
This is the output:
{Leonardo=Dicaprio, Katharine=Cornell, Joe=Lipari, Tom=Hanks, Robert=De, Susan=Sarandon, John=Laughlin, Mark=Zuckerberg, Barack=Obama, Welker=White, Helen=Hayes}
Does anyone know how to fix this please? Also how to seperate them so it actually looks like a list?

EDIT
I think you would just change your line:
String[] columns = input.nextLine().split(" ");
to:
String[] columns = input.nextLine().split(Pattern.quote(" | "));
Then column[0] would be the name on the left, and column[1] would be the name and movie title on the right.
Note that you'll need to import java.util.regex.Pattern; to do this

Related

Groovy createCriteria issue with joined table

I have a domain class Coach which has a has many relationship to another domain class CoachProperty.
Hibernate/Grails is creating a third joined table in the database.
In the example below I am trying to fetch the coaches which both have foo AND bar for their text value. I have tried different solutions with 'or' and 'and' in Grails which either returns an empty list or a list with BOTH foo and bar.
Coach:
class Coach {
static hasMany = [ coachProperties : CoachProperty ]
CoachProperty:
class CoachProperty {
String text
boolean active = true
static constraints = {
text(unique: true, nullable: false, blank: false)
}
}
Joined table which is being auto-created and I populated with some data, in this example I am trying to fetch coach 372 since that coach has both 1 and 2 i.e foo and bar:
+---------------------------+-------------------+
| coach_coach_properties_id | coach_property_id |
+---------------------------+-------------------+
| 150 | 2 |
| 372 | 1 |
| 372 | 2 |
| 40 | 3 |
+---------------------------+-------------------+
Inside Coach.createCriteria().list() among with other filters. This should return coach 372 but return empty:
def tempList = ["foo", "bar"]
coachProperties{
for(String temp: tempList){
and {
log.info "temp = " + temp
ilike("text",temp)
}
}
}
I seem to remember this error. Was something about not being able to use both nullable & blank at the same time.Try with just 'nullable:true'
I had to create a workaround with executeQuery where ids is the list containing the id's of the coachproperties i was trying to fetch.
def coaches = Coach.executeQuery '''
select coach from Coach as coach
join coach.coachProperties as props
where props.id in :ids
group by coach
having count(coach) = :count''', [ids: ids.collect { it.toLong()
}, count: ids.size().toLong()]
or{
coaches.each{
eq("id", it.id)
}
}

How to match a regex with words followed by date?

I'd like to write a regex to match sentences like these:
"I rated Minions (2015)..."
"I rated Beauty and the Beast (2015)..."
I've tried a regex like:
I rated \\w+ \\(\\b(18|19|20)\\d{2}\\b\\)
but it works only in the first case, when the title is a single word.
Between "I rated" and the year there is a title of a movie with no fixed length. Could you help me?
Try using regex like
\[^.?!(]* \\((18|19|20)\\d{2}\\)\
OR
\\w+ (?:\\w+ )*\\((?:1[89]|20)\\d{2}\\)
Assuming that:
you don't really need to validate the year
your text has mixed spurious sentences, as opposed to one-liner "I rated..."
you want to do something with the movie title and year separately
You can use:
String text = "I rated Minions (2015)... I like turtles. "
+ "I rated Beauty and the Beast (2015)... "
+ "I rated rare live footage of Louis XVI being beheaded (1789)";
// | starts with "I rated"
// | | group 1 with the title
// | | | open parenthesis
// | | | | group 2 with non-validated year
// | | | | | closing parenthesis
// | | | | |
Pattern pattern = Pattern.compile("I rated (.+?) \\((\\d+)\\)");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.printf(
"Title: %s - Year: %s%n",
// title is back-referenced as group 1
matcher.group(1),
// year is back-referenced as group 2
matcher.group(2)
);
}
... which will return:
Title: Minions - Year: 2015
Title: Beauty and the Beast - Year: 2015
Title: rare live footage of Louis XVI being beheaded - Year: 1789

Subtotaling an arraylist that was imported from a csv file

I'm making a school project for a java coding class and need some help
I've imported a CSV file with some information on it that has been separated into an ArrayList and wish to total each different category in the file.
right now my output is:
Item | Category | Amount | Price | Location
Carrots | Food | 12 | $2 | Walmart
Potatoes | Food | 15 | $3 | Walmart
T-Shirt | Clothes | 1 | $16 | Walmart
Toothbrush | Cleaning | 2 | $2 | Walmart
my goals are to get subtotals for each category such as:
Item | Category | Amount | Price | Location
Carrots | Food | 12 | $2 | Walmart
Potatoes | Food | 15 | $3 | Walmart
Subtotal for Food is: $69
T-Shirt | Clothes | 1 | $16 | Walmart
Subtotal for Clothes is: $16
Toothbrush | Cleaning | 2 | $2 | Walmart
Subtotal For Cleaning is: $4
and then to eventually have the whole thing totalled at the end and displayed like this:
Item | Category | Amount | Price | Location
Carrots | Food | 12 | $2 | Walmart
Potatoes | Food | 15 | $3 | Walmart
Subtotal for Food is: $69
T-Shirt | Clothes | 1 | $16 | Walmart
Subtotal for Clothes is: $16
Toothbrush | Cleaning | 2 | $2 | Walmart
Subtotal For Cleaning is: $4
Total is: $89
Here is my code right now:
public static void main(String[] args) {
ArrayList<output> csvstuff = new ArrayList<output>();
String fileName = "Project2.csv";
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()) {
String data = inputStream.next();
String[] values= data.split(",");
String Item = values[0];
String Category = values[1];
String Amount = values[2];
String Price = values[3];
String Location = values[4];
String format = "%-10s |%10s |%10s |%10s |%10s\n";
System.out.printf(format, values[0], values[1], values[2], values[3], values[4]);
output _output = new output(Item,Category,Amount,Price,Location);
csvstuff.add(_output);
}
inputStream.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Instead of printing values while reading in the loop, add it to arraylist as you have done. Then sort the data based on Category type. Refer to comparable and comparator in java.
And now you can simply iterate over the list and keep counting the subtotal for each category.
Useful link: Comarator v/s Comparable
Sort all rows by their category.
Walk the sorted list and keep a subtotal count.
If an item is in a different category than the previous one, emit a subtotal row and clear the subtotal value. (You'll also have to do this once after the last row.)
Then emit a line describing the current row.
To emit a grand total, simply keep another total that is updated with each row and never cleared.

Paragraph to Table in Different Columns

I want to create a program such that if I have inserted a paragraph in a text area, I want certain parts of it to be put in the table in different columns. For example the statement is:
My name is James Olson. I am 21 years old. I am a doctor. I live in Canterville, Bacon Street, London.
Then the table should automatically look like:
| Name | Age | Profession | Area Name | Street Name | Area |
James | 21 | Doctor | Canterville | Bacon Street | London |
I also want to know which language would go the best - Python or Java.
Yes it is certainly possible to do so and I would personally prefer Python to do the Job.
I've written the code, it is not the best or the most efficient code but it will surely do the job but there is a catch in my code. It will only work if the sequence and pattern of your sentence is same. The pattern should be exactly like the one you provided in the example.
If you want the code to work for multiple sentences, a slight change in the code with a loop can do the work.
import pandas as pd
my_sent = "My name is James Olson. I am 21 years old. I am a doctor. I live in Canterville, Bacon Street, London."
my_words = my_sent.split()
my_stopwords = ['My', 'name', 'is', 'I', 'am', 'years', 'old.', 'I', 'am', 'a', 'I', 'live', 'in',]
cleaned_stopwords = []
useful_words = []
for temp in my_stopwords:
cleaned_stopwords.append(temp.lower().strip())
for word in my_words:
if word.lower().strip() not in cleaned_stopwords:
useful_words.append(word.title().strip(".").strip(","))
name = useful_words[0] + " " + useful_words[1]
street = useful_words[5] + " " + useful_words[6]
useful_words.pop(0)
useful_words.pop(0)
useful_words.insert(0, name)
useful_words.pop(4)
useful_words.pop(4)
useful_words.insert(4, street)
all_columns = ["Name", "Age", "Profession", "Area Name", "Street Name", "Area"]
my_df = pd.DataFrame([useful_words], columns = all_columns)
Output:
Name Age Profession Area Name Street Name Area
0 James Olson 21 Doctor Canterville Bacon Street London

In Tests none of the threads execute the method

I got a project, but I see difficulties. https://github.com/siqqQ/ILTasks/tree/master/busThread This is the project(4 files). I am worried about this test
`
void areAllPeopleWithDistinctTicket() throws InterruptedException {
int numberOfPeople = 50;
TicketManager t = TicketManager.getTicketManager(numberOfPeople);
Set<Integer> persons = new HashSet<>();
t.start();
for (Person person : t.getPersons()) {
if(!persons.add(person.getTicketNumber()) && person.getTicketNumber()!=null){
fail("There are people with same tickets");
}
}
}
When I test it, it shows me in the console that all tickets are SoldOut and none of the people are on the bus.
`
Name : Person 1 | Ticket: SoldOut
Name : Person 2 | Ticket: SoldOut
Name : Person 3 | Ticket: SoldOut
Name : Person 4 | Ticket: SoldOut
Name : Person 5 | Ticket: SoldOut
Name : Person 6 | Ticket: SoldOut
Name : Person 7 | Ticket: SoldOut
Name : Person 8 | Ticket: SoldOut
Name : Person 9 | Ticket: SoldOut
Name : Person 10 | Ticket: SoldOut
Name : Person 11 | Ticket: SoldOut
Name : Person 12 | Ticket: SoldOut...
`
I will be happy if someone can explain me why is this happening and provide some solution to this.
In TicketManager, you're calling printBusArrangment() without waiting for the threads to finish executing. Try this:
sendAllPeopleToBuyTicket(personsThreads, persons);
for (Thread thread : personThreads) {
thread.join();
}
printBusArrangment(persons);

Categories