Reverse Names Given [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm looking to reverse the names found in a list given to me (EDIT: given to me from a web scraping of a website) Again not homework
Small sample of list:
Baynes, Aron
Bazemore, Kent
Beal, Bradley
Beasley, Malik
Beasley, Michael
Belinelli, Marco
Bell, Jordan
Bembry, DeAndre'
I need them as Aron Baynes (or Aron,Baynes)
Weirdly people think this is homework problem. THIS IS NOT. I am using NBA player names in a program I have written. I can not post code as the code used is 1000s of lines long. I simply need the ability to reverse the name order in a quick manner compared to my attempts
What I tried: for loops using , as a index then working back and forth using substrings. This did not work well for a list of strings as given above

If you have all names in file (e.g. names.txt):
Baynes, Aron
Bazemore, Kent
Beal, Bradley
Beasley, Malik
Beasley, Michael
Belinelli, Marco
Bell, Jordan
Bembry, DeAndre'
You can:
Read line
split line (using separator)
display in reverse way
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
// File name
String fileName = "names.txt";
String separator = ", ";
String line;
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
while ((line = bufferedReader.readLine()) != null) {
String[] elements = line.split(separator);
if (elements.length == 2) {
System.out.printf("%s %s\n", elements[1], elements[0]);
} else {
System.out.println("Wrong line: " + line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Or using List instead of files:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList(
"Baynes, Aron",
"Bazemore, Kent",
"Beal, Bradley",
"Beasley, Malik",
"Beasley, Michael",
"Belinelli, Marco",
"Bell, Jordan",
"Bembry, DeAndre'"
));
String separator = ", ";
// Using loop
for (String person : list) {
String[] elements = person.split(separator);
if (elements.length == 2) {
System.out.printf("%s %s\n", elements[1], elements[0]);
} else {
System.out.println("Wrong line: " + person);
}
}
// Using stream
list.forEach(person -> {
String[] elements = person.split(separator);
if (elements.length == 2) {
System.out.printf("%s %s\n", elements[1], elements[0]);
} else {
System.out.println("Wrong line: " + person);
}
});
}
}

Related

How to iterate over List of Lists in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am reading a CSV file into a List<String>. However, my program creates a new List for each row in the CSV file. structure of the CSV file is shown below:
[KI , -3.370417, -168.734039, Kiribati]
[KM , -11.875001, 43.872219, Comoros]
[KN , 17.357822, -62.782998, Saint Kitts and Nevis]
[KP , 40.339852, 127.510093, North Korea]
[KR , 35.907757, 127.766922, South Korea]
[KW , 29.31166, 47.481766, Kuwait]
[KY , 19.513469, -80.566956, Cayman Islands]
[KZ , 48.019573, 66.923684, Kazakhstan]
[LA , 19.85627, 102.495496, Laos]
I want to be able to iterate over each of these lists and access items such as the "South Korea" or "KI".
However I cannot find an efficient way of doing so. My attempt is shown below for traversing the Lists in the method distance():
import java.util.*;
import java.io.*;
public class Main {
public static void distance(List<String> list) {
//attempt
for (List row : list) {
for (Object item : row) {
System.out.println(item + "\t");
}
System.out.println();
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
String file = "countries.csv";
List<String> countries;
BufferedReader reader = null;
String line = "";
reader = new BufferedReader(new FileReader(file));
while ( (line = reader.readLine()) != null ) {
List<String> nodes = Arrays.asList(line.split(","));
countries = nodes;
//System.out.println(countries);
// System.out.println(Arrays.toString(nodes));
}
System.out.println();
distance(countries);
}
}
Is there a way of iterating over and accessing elements of List of Lists?
.
I don't quite understand your question, but in any case, your code does not compile because you are treating countries as a list of lists while it is only a list of String! here is a working version of your application:
package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void distance(List<List<String>> list) {
for (List row : list) {
for(Object item: row)
System.out.println(item + "\t");
System.out.println();
}
}
public static void main(String[] args) throws IOException {
String file = "countries.csv";
List<List<String>> countries = new ArrayList<>();
BufferedReader reader = null;
String line = "";
reader = new BufferedReader(new FileReader(file));
while ( (line = reader.readLine()) != null ) {
List<String> nodes = Arrays.asList(line.split(","));
countries.add(nodes);
//System.out.println(countries);
// System.out.println(Arrays.toString(nodes));
}
System.out.println();
distance(countries);
}
}
I changed countries = nodes; to countries.add(nodes); which creates a list of List<string>, now if you want to access the last element of the inner list, you can do so like this:
System.out.println("Country: " + row.get(3));
I believe you would benefit a lot by reading on:
how to initialize objects in Java.
data structures such as Array, LinkedList and ArrayList.
You can use jackson (here you'll find documention of it https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv) to read CSV file.
you can try this code, in this way you can iterate the list easily.
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class CsvUtils {
private final static CsvMapper mapper = new CsvMapper();
/**
* function to read SCV
* #param clazz {#link Class}
* #param file {#link File}
* #param <T> {#link T}
* #return List of object
* #throws IOException must catch it
*/
public static <T> List<T> read(Class<T> clazz, File file) throws IOException {
CsvSchema schema = mapper.schemaFor(clazz).withHeader().withColumnSeparator(',');
return mapper.readerFor(clazz).with(schema).<T>readValues(file).readAll();
}
}

Error parsing this csv file

I am trying to parse this csv file but when i got to print it I get "Input length =1" as the output. Here is my code: Can anyone provide an explanation as to why this is happening?
try {
List<String> lines = Files.readAllLines(Paths.get("src\\exam1_tweets.csv"));
for(String line : lines) {
line = line.replace("\"", "");
System.out.println(line);
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
You want this change
List<String> lines = Files.readAllLines(Paths.get("src\\exam1_tweets.csv"),
StandardCharsets.ISO_8859_1);
It was encoding issue please read this.
To see full cause of errors you should use e.printStackTrace() in catch block.
java code:
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Sof {
public static final String USER_DIR = "user.dir";
public static void main(String[] args) {
try {
List<String> lines = Files.readAllLines(
Paths.get(System.getProperty(USER_DIR) + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "exam1_tweets.csv"),
StandardCharsets.ISO_8859_1);
for (String line : lines) {
line = line.replace("\"", "");
System.out.println(line);
}
} catch (Exception e) {
System.out.println("ERROR" + e.getMessage());
}
}
}
console:
Handle,Tweet,Favs,RTs,Latitude,Longitude
BillSchulhoff,Wind 3.2 mph NNE. Barometer 30.20 in, Rising slowly. Temperature 49.3 °F. Rain today 0.00 in. Humidity 32%,,,40.76027778,-72.95472221999999
danipolis,Pausa pro café antes de embarcar no próximo vôo. #trippolisontheroad #danipolisviaja Pause for? https://....,,,32.89834949,-97.03919589
KJacobs27,Good. Morning. #morning #Saturday #diner #VT #breakfast #nucorpsofcadetsring #ring #college? https://...,,,44.199476,-72.50417299999999
stncurtis,#gratefuldead recordstoredayus ?????? # TOMS MUSIC TRADE https://...,,,39.901474,-76.60681700000001
wi_borzo,Egg in a muffin!!! (# Rocket Baby Bakery - #rocketbabybaker in Wauwatosa, WI) https://...,,,43.06084924,-87.99830888
KirstinMerrell,#lyricwaters should've gave the neighbor a buzz. Iv got ice cream and moms baked goodies ??,,,36.0419128,-75.68186176
Jkosches86,On the way to CT! (# Mamaroneck, NY in Mamaroneck, NY) https://.../6rpe6MXDkB,,,40.95034402,-73.74092102
tmj_pa_retail,We're #hiring! Read about our latest #job opening here: Retail Sales Consultant [CWA MOB] Bryn Mawr PA - https://.../bBwxSPsL4f #Retail,,,40.0230237,-75.31517719999999
Vonfandango,Me... # Montgomery Scrap Corporation https://.../kpt7zM4xbL,,,39.10335,-77.13652 ....
I've made a csv parser/writer , easy to use thanks to its builder pattern
It parses csv file and gives you list of beans
here is the source code
https://github.com/i7paradise/CsvUtils-Java8/
I've joined a main class Demo.java to display how it works
let's say your file contains this
Item name;price
"coffe ""Lavazza""";13,99
"tea";0,00
"milk
in three
lines";25,50
riz;130,45
Total;158
and you want to parse it and store it into a collection of
class Item {
String name;
double price;
public Item(String name, double p) {
// ...
}
//...
}
you can parse it like this:
List<Item> items = CsvUtils.reader(Item.class)
//content of file; or you can use content(String) to give the content of csv as a String
.content(new File("path-to-file.csv"))
// false to not include the first line; because we don't want to parse the header
.includeFirstLine(false)
// false to not include the last line; because we don't want to parse the footer
.includeLastLine(false)
// mapper to create the Item instance from the given line, line is ArrayList<String> that returns null if index not found
.mapper(line -> new Item(
line.get(0),
Item.parsePrice(line.get(1)))
)
// finally we call read() to parse the file (or the content)
.read();

String pattern wit ha dollar present

I have the below data in a text file.
CS##NEWSLTR$$
RY##GLMALAW$$
VW##NWL$$
VW##GLS$$
IS##4$$
ST##NJ$$
ST##NY$$
SORTX##0050004018001$$
RC##18 No. 4 GLMALAW 1$$
CR##18 No. 4 M & A Law. 1$$
SO3##The M & A Lawyer$$
DL##April, 2014$$
TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT
STRATEGY$$
here i'm actually trying to fetch these values into a java array with the below code.
package strings;
import com.sun.org.apache.xalan.internal.xsltc.runtime.BasisLibrary;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
*
* #author u0138039
*/
public class Strings {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner inFile1 = null;
try {
inFile1 = new Scanner(new File("C:\\Users\\u0138039\\Desktop\\Adhil\\WDA.TP.GLASSER.IB.F486806.A.D140605.T.txt")).useDelimiter("$\\\\\\\\\\\\$");
} catch (FileNotFoundException ex) {
Logger.getLogger(Strings.class.getName()).log(Level.SEVERE, null, ex);
}
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
tokens.add(inFile1.nextLine());
}
String[] tokenArray = tokens.toArray(new String[0]);
for (int i = 0; i < tokenArray.length; i++) {
String s = tokenArray[i];
System.out.println("a["+i+"]" +tokenArray[i]);
}
}
}
here my concept is that the line ends with a $$ and this is how it should be stored in an array, but when i run the above program i get the below output.
a[0]CS##NEWSLTR$$
a[1]RY##GLMALAW$$
a[2]VW##NWL$$
a[3]VW##GLS$$
a[4]IS##4$$
a[5]ST##NJ$$
a[6]ST##NY$$
a[7]SORTX##0050004018001$$
a[8]RC##18 No. 4 GLMALAW 1$$
a[9]CR##18 No. 4 M & A Law. 1$$
a[10]SO3##The M & A Lawyer$$
a[11]DL##April, 2014$$
a[12]TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT
a[13] STRATEGY$$
here a[12] and a[13] belong to same array number(index), but here these are divided into 2.
The expected output is as below(since the end $$ of a[12] came in a[13])
a[0]CS##NEWSLTR$$
a[1]RY##GLMALAW$$
a[2]VW##NWL$$
a[3]VW##GLS$$
a[4]IS##4$$
a[5]ST##NJ$$
a[6]ST##NY$$
a[7]SORTX##0050004018001$$
a[8]RC##18 No. 4 GLMALAW 1$$
a[9]CR##18 No. 4 M & A Law. 1$$
a[10]SO3##The M & A Lawyer$$
a[11]DL##April, 2014$$
a[12]TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT STRATEGY$$
please let me know where am i going wrong and how to fix it.
Thanks
Forget the useDelimiter
List<String> tokens = new ArrayList<String>();
int next = 0;
while (inFile1.hasNext()) {
String line = inFile1.nextLine();
if( next >= tokens.size() ){
tokens.add( line );
} else {
tokens.set( next, tokens.get(next) + line );
}
if( line.endsWith( "$$" ) ) next++;
}
You're issuing a inFile1.nextLine() so naturally, the strings in a[12] and a[13] would be separated.
One approach I can think of is putting the content of the file in a String object, then do a split using "\$\$" .
String s = "Hello$$World$$Sample$$";
for(String sa: s.split("\\$\\$")) {
System.out.println(sa);
}
Output:
Hello
World
Sample
But this will not include the trailing "$$" since you used it in the split. You can easily add that do the end of your string, but this is just one approach.
Hope this helps.
String partialLine = null;
while (inFile1.hasNext()) {
String line = inFile1.nextLine();
if (partialLine != null) {
line = partialLine + line;
partialLine = null;
}
if (line.endsWith("$$") {
tokens.add(line);
} else {
partialLine = line;
}
}
if (partialLine != null) {
// Probably empty line.
}
A bit of buffering: not adding a partial line (missing $$), but keeping it in partialLine.
As you see even several partial lines would work.

Group map elements and sum their values in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I read the below data from a CSV file.
Pedro|groceries|apple|1.42
Nitin|tobacco|cigarettes|15.00
Susie|groceries|cereal|5.50
Susie|groceries|milk|4.75
Susie|tobacco|cigarettes|15.00
Susie|fuel|gasoline|44.90
Pedro|fuel|propane|9.60
I wanted to group the expenses of each customer like
Expense of Pedro:
Groceries - 1.42
fuel - 9.62
I also wanted to group the sum of the expense for each customer like
Total expense for each customer is:
Pedro - (1.42 + 9.60)
Nitin - 15.00
Susie - (5.50 + 4.75 + 15.00 + 44.90)
Can someone help me in how will I group the elements and sum their values.
I am able to read the file and print separate values. I mapped each group member with their expenses. But don't know how to sum up their values
can Someone help me?
This is my code, im sure this is incorrect
static String[] inputArray ;
public static void main(String[] args) throws IOException {
groceryReport gr = new groceryReport();
try {
gr.readFile();
System.out.println(gr.customerPurchase(inputArray).toString());
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#SuppressWarnings("null")
private void readFile() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\....\\grocery.csv"));
String input= "";
try{
System.out.println("The total revenue for each customer is:");
while((input = br.readLine()) != null )
{
inputArray= input.split("\\|");
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String customerPurchase(String[] inputArray){
String sum = "" ; float sum1=0; float sum2 = 0;
ArrayList<String[]> alist = new ArrayList<String[]>();
alist.add(inputArray);
String value = "";
System.out.println(alist);
Map<String, String> map = new HashMap<String, String>();
map.put(inputArray[0], inputArray[3]);
System.out.println(map.get(inputArray));
Iterator ite = map.entrySet().iterator();
while (ite.equals("Susie"))
ite.next();
value = map.get("Susie");
sum = sum+ value;
return sum;
}
My solution can be found here, but I will give you a short breakdown of it.
First of all I created a class names Purchase as an abstraction for each of the lines in your csv file. This is just a simple class to group together the information around a purchase (item type, specific item and price).
The createReport method takes the csv lines as input, and will return a datastructure a Map<String, List<Purchase>, the key to the map is going to be the names of the persons, and their associated purchases. If I wanted to fetch all purchases made by Pedro I would simply use mapVariable.get("Pedro"); and it would return a List<Purchases> of all Pedro's purchases.
Finding the sum of Pedro's purchases is therefore a simple task, as can be seen in the sum method.
This ends up giving a report looking like this:
---------------------------------------
Name. Nitin
---------------------------------------
tobacco 15.0
---------------------------------------
Total: 15.0
---------------------------------------
---------------------------------------
Name. Pedro
---------------------------------------
groceries 1.42
fuel 9.6
---------------------------------------
Total: 11.02
---------------------------------------
---------------------------------------
Name. Susie
---------------------------------------
groceries 5.5
groceries 4.75
tobacco 15.0
fuel 44.9
---------------------------------------
Total: 70.15
---------------------------------------
In object oriented languages, when you want to group specific pieces of data, this is accomplished by using classes.
Im assuming this is a homework assignment and so I can't give full details. But you want a person class that contains fields for the info you want. From there you can iimplemet methods to output exactly what you want?

Is there a Java API or shortcut for a state name lookup/find? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I'm writing a program that takes in a string, a state name (for example New York), and outputs the corresponding abbreviation (e.g. NY). My program considers all 50 states, so my first thought was to use a boatload of if/else if statements, but now I'm thinking there's gotta be a better way...a faster way...without so much seemingly redundant code.
Snippet:
if (dirtyState.equalsIgnoreCase("New York")) {
cleanState = "NY";
} else if (dirtyState.equalsIgnoreCase("Maryland")) {
cleanState = "MD";
} else if (dirtyState.equalsIgnoreCase("District of Columbia")) {
cleanState = "DC";
} else if (dirtyState.equalsIgnoreCase("Virginia")) {
cleanState = "VA";
} else if (dirtyState.equalsIgnoreCase("Alabama")) {
cleanState = "AL";
} else if (dirtyState.equalsIgnoreCase("California")) {
cleanState = "CA";
} else if (dirtyState.equalsIgnoreCase("Kentuky")) {
cleanState = "KY";
// and on and on...
Is there an API that could make this process simpler? A shortcut perhaps?
Any feedback is greatly appreciated and thanks in advance =)
You could use a TreeMap which allows you to use a custom comparator that is case insensitive. It would look like this:
Map<String, String> states = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
states.put("New York", "NY");
states.put("Maryland", "MD");
//etc.
And to retrieve an abbreviation:
String abbreviation = states.get("new york");
System.out.println(abbreviation); //prints NY
If you're using Java 7 you can use strings in a switch statement, e.g.:
switch (dirtyState.toLowerCase())
{
case "new york": cleanState = "NY"; break;
case "maryland": cleanState = "MD"; break;
// so on...
}
It would be better to grab a city code list and put it in a properties file like:
New York=NY
Maryland=MD
District of Columbia=DC
Virginia=VA
Then load the content in a Properties and loop on its entries (it extends HashTable):
Properties cityCodes = new Properties()
citycodes.load(new FileInputStream(...));
for(Entry<String,String> entry : cityCodes.entrySet()){
if(dirtyState.equalsIgnoreCase(entry.getKey())){
cleanState = entry.getValue();
}
}
Here is a working example :
public static void main(String[] args) throws Exception{
Properties cityCodes = new Properties();
cityCodes.load(new FileInputStream("/path/to/directory/cityCodes.properties"));
System.out.print(getCode("Maryland",cityCodes));
}
public static String getCode(String name, Properties cityCodes){
for(Map.Entry<Object,Object> entry : cityCodes.entrySet()){
String cityName=(String)entry.getKey();
String cityCode=(String)entry.getValue();
if(name.equalsIgnoreCase(cityName)){
return cityCode;
}
}
return null;
}
Output:
MD
You could use an enum:
public enum State {
AL("Alabama"), CA("California"), NY("New York");
private State(String name) {
this.name = name;
}
private String name;
static String findByName(String name) {
for ( int i = 0; i != values().length; ++i ) {
if ( name.equalsIgnoreCase(values()[i].name))
return values()[i].toString();
}
throw new IllegalArgumentException();
}
}
public class StateTest {
public static void main(String[] args) {
String name = "New York";
System.out.println(name + ": " + State.findByName(name));
}
}

Categories