With the code below, I am trying to write the key and values of the male and female map to an existing file.
But it shows the following error.
Can somebody help me please.
ERROR# Map.Entry entry = (Map.Entry) entryIter.next();
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at test.main(test.java:83)
Code
public static void main(String[] args) {
Map<String, List<String>> MaleMap = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> FemaleMap = new LinkedHashMap<String, List<String>>();
try {
Scanner scanner = new Scanner(new FileReader(".txt"));
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
String[] column = nextLine.split(":");
if (column[0].equals("Male") && (column.length == 4)) {
MaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
} else if (column[0].equals("Female") && (column.length == 4)) {
FemaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
}
}
Set<Entry<String, List<String>>> entries = MaleMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries.iterator();
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object maleName = key;
Object maleAge = null;
Object maleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(key + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object maleName = key;
Object maleAge = value1;
Object maleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write(maleAge + "." + maleID + "##;" + "\n"
+ " :class :" + maleName);// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Set<Entry<String, List<String>>> Fentries = FemaleMap.entrySet();
Iterator<Entry<String, List<String>>> FentryIter = Fentries.iterator();
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object Fkey = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = null;
Object femaleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(Fkey + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = value1;
Object femaleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write("map:" + femaleName + " a :Bridge;" + "\n"
+ ":property" + femaleAge + ";" + "\n"
+ ":column" + " " + femaleID + " " + ";");// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Map.Entry entry = (Map.Entry) entryIter.next(); in your second loop is breaking.
After the first while loop that iterates through the males, your iterator has reached the end of the set, and will break when you try to call next().
What you actually want to do is iterate through your females.
Change the line to iterate with your FentryIter:
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) FentryIter.next();
This is most likely the result of copy-paste code, and you need to be careful when doing this. I would recommend re-factoring your code since so much of it is duplicated.
Related
My problem is in the part where I'm doing the "if/else" conditions, when I call the function that will perform the comparisons and will define if the test passed or not and will send some information, I'm receiving null.
Problems are among the asterisks. If anyone can help me
This is my code :
public static void fxSpot_GBP_JPY(TradeData data, TradeData output) throws Exception {
if (data == null) {
fail("The input data object was not correctly filled");
}
if (output == null) {
fail("The output data object was not correctly filled");
}
//Used to set the comment, the status and update to JIRA
FieldsJSON fields = new FieldsJSON();
String assertionError = "";
List<String> inputs = new ArrayList<String>();
List<String> outputs = new ArrayList<String>();
String newDate = Utils.formatTimeZoneMinute(data.getTradeDate());
String asOfTrade = Utils.formatTimeZoneMinute(data.getAsOfTradeDate());
String executionDate = Utils.formatTimeZoneMinute(output.getExecutionDateTime());
try {
//Add the data in the list
inputs.add(data.getTransactionNumber()); outputs.add(output.getBloombergId());
inputs.add(newDate); outputs.add(output.getTradeDate());
inputs.add(asOfTrade); outputs.add(executionDate);
inputs.add(data.getSettlementDate()); outputs.add(output.getValueDate());
inputs.add(data.getTradeAmount()); outputs.add(output.getAmount2());
inputs.add(data.getCustomerAccountCounterparty()); outputs.add(output.getMiPartyId());
inputs.add(data.getPrincipalLoanAmount()); outputs.add(output.getAmount());
inputs.add(data.getSecurityPrice()); outputs.add(output.getRate());
inputs.add(data.getISOCodeOf1stCurrency()); outputs.add("BRL");//output.getCurrency2()
inputs.add(data.getISOCodeOf2ndCurrency()); outputs.add(output.getCurrency1());
//Compare values
System.out.println("-------------------");
int y = 0;
int x = 0;
for(String input : inputs) {
for(String out : outputs) {
if(y == x) {
if(input.equals(out)) {
WriterCSV.setOk("Ok");
**String comment = input + " = " + out;
fields.setComment(comment);
fields.setStatus("PASS");**
System.out.println("ok - " + input + " = " + out);
}else {
WriterCSV.setOk("not Ok");
**String comment = input + " = " + out;
fields.setComment(comment);
fields.setStatus("FAIL");**
System.out.println("not Ok - " + input + " = " + out);
}
}
x = x+1; // count of the list of output
}
y = y+1; // count of the list of inputs
x = 0; // reset to 0 the count of outputs
}
// evidence with the name and value of fields compared
WriterCSV.reportSpot_CSV(data,output);
}
Here is my test:
#Test
#Tag("compare")
public void CompareSpot() throws Exception {
//Create a list to read the CSVfile
List<DTOTradeData> dto;
//Used to get the TradeData of list dto.
DTOTradeData dtd = new DTOTradeData();
// Read a csvFile and return a list with the values to new xml
dto = CSVReader.readCSV("spot.csv");
//The xpath of xml
FileDriverSpot spot = new FileDriverSpot();
FileDriver output = new FileDriverSpotOutput();
FieldsJSON fields = new FieldsJSON();
//new xml = dataInput and the outputFile = dataOutput
TradeData dataInput = new TradeData();
TradeData dataOutput = new TradeData();
for (int i = 0; i < dto.size(); i++) {
dtd = dto.get(i); // get TradeData
dtd.getTradeData().setDriver(spot); // set the driver
if (fileExist(Setup.xmlPath + dtd.getInputFile() + ".xml")) {
dataInput = Reader.read(spot, Setup.xmlPath + dtd.getInputFile() + ".xml");
dataOutput = Reader.read(output, Setup.spotPath + dtd.getOutputFile());
try {
// make the comparison
**FunctionalTest.fxSpot_GBP_JPY(dataInput, dataOutput);**
}
catch(AssertionError e) {
String comment = e.toString();
fields.setComment(comment);
}
} else {
fail("The file: " + dtd.getTemplateFile()
+ " needs to go through the writing process before being compared.");
}
//Convert the file to base64
String inputData = UpdateTestStatus.convertToBase64(Setup.xmlPath + dtd.getInputFile() + ".xml");
String outputData = UpdateTestStatus.convertToBase64(Setup.spotPath + dtd.getOutputFile());
String evidenceCompared = UpdateTestStatus.convertToBase64(Setup.reportPath+"ReportSpot.csv");
System.out.println(UpdateTestStatus.updateTestRun(**fields.getStatus(),fields.getComment()**,
inputData,dtd.getInputFile()+ ".xml", //data of the XML and the name of the file
outputData,dtd.getOutputFile(),
evidenceCompared,"ReportSpot.csv",
Setup.testExec, dtd.getJiraId()).asString()); // ID testExecution and ID of
}
}
The test and the code under test each create a separate instance of FieldsJSON. Data set in one instance will not be visible in the other (unless the data is declared static, in which case there's no need to create instances).
You can fix this by using a single instance, either passed to the fxSpot_GBP_JPY method from the test, or returned from that method to the test.
I used the following script to read a CSV file and extract suspicious data in descending order. I am trying to print out the result of the highest occurrence which is the first result showing. Should I specify it in the map script? Can I utilize println to show that?
public class Part2 {
public static void main(String[] args) {
try (Scanner csvData = new Scanner(
new File("C:\\Users\\amber\\Documents\\IN300_Dataset1.csv"))) {
List<String> list = new ArrayList<String>();
while (csvData.hasNext()) {
list.add(csvData.nextLine());
}
String[] tempArray = list.toArray(new String[1]);
String[][] csvArray = new String[tempArray.length][];
String combined_list[] = new String[tempArray.length];
String myData = null;
for(int i=0; i < tempArray.length; i++) {
if(i == 0) continue;
csvArray[i] = tempArray[i].split(",");
if(csvArray[i][4].matches("^\"[a-zA-Z].*\"")) {
continue;
}
else {
myData= csvArray[i][2] + " " +
csvArray[i][3] + " " +
csvArray[i][4] + " " +
csvArray[i][5] + " " +
csvArray[i][6];
combined_list[i] = myData;
}
}
getOccurences("Suspicious Result(s)", combined_list);
}
catch(Exception e) {
System.out.println(e);
}
}
private static void getOccurences(String message, String[] myArray) {
Map<String, Integer> map = new HashMap<>();
for (String key : myArray) {
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}
}
Map<String, Integer> sortedMap =
map.entrySet().stream()
.sorted(Collections.reverseOrder(Entry.comparingByValue()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
printMap(message, sortedMap);
}
private static void printMap(String message, Map<String, Integer> map)
{
System.out.println();
System.out.println();
System.out.println("Printing" + message);
System.out.println();
map.forEach((key, value) -> {
if(key != null && value > 100) {
System.out.println(key + "appeared " + value + " times(s).");
}
});
}
}
Here is a sample of my results (The bold text is the result that I only want to display):
PrintingSuspicious Result(s)
00:28:00:01:00:00 02:00:00:00:45:00 0x4006 44 Ethernet IIappeared 7536 times(s).
209.99.61.21 192.168.1.24 UDP 1359 17212 > 52797 Len=1309appeared 2990 times(s).
192.168.1.24 209.99.61.21 UDP 170 52797 > 17212 Len=128appeared 2905 times(s).
209.99.61.21 192.168.1.24 UDP 1351 17212 > 52797 Len=1309appeared 2851 times(s).
If you want to display only the first result, just quit the loop after displaying the first element (you'll have to use normal for loop instead of using forEach to be able to break):
private static void printMap(String message, Map<String, Integer> map)
{
System.out.println();
System.out.println();
System.out.println("Printing" + message);
System.out.println();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getKey() != null && entry.getValue() > 100) {
System.out.println(entry.getKey() + "appeared " + entry.getValue() + " times(s).");
break;
}
}
}
I'm able correctly to create and to write into a new file, but don't in a second one or more.
What's wrong?
int numbOfFile = 0;
PrintWriter bw = new PrintWriter("C:path\test" + numbOfFile + ".csv");
for (Map.Entry<String, List<Integer>> entry : inSorting.entrySet()) {
String key = entry.getKey();
numbOfFile++;
if (!(numbOfFile % 3 == 0)) {
bw.println(key + " ");
} else {
bw.close();
new PrintWriter(""C:path\test" + numbOfFile + ".csv"");
bw.println(key + " ");
}
}
bw.close();
I am trying to get v8 from the third array inside following arraylist
String[][] test = {
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7", "v8"}
};
ArrayList<String[]> test2= new ArrayList<String[]>(Arrays.asList(test));
Log.e("v1: ", "" + test2.get(0));
for (int j = 0; j <= test2.size(); j++) {
for (String[] arrays: test2) {
for (String string2 : arrays) {
if (string2.equalsIgnoreCase("v8")) {
Log.e("LOOOOOOOOOG", "" + test2.indexOf("v8")); // 3
}else {
Log.e("LOOOOOOOOOG", "Cant find it!!");
}
}
}
}
How would i do this?
I currently just get either -1 or Cant find it!!
I am trying to solve the above problem to solve the following HashMap problem.
public static void updateJSONdata() {
mEmailList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_EMAILS_URL);
try {
mEmails = json.getJSONArray("info");
// looping through all emails according to the json object returned
for (int i = 0; i < mEmails.length(); i++) {
JSONObject c = mEmails.getJSONObject(i);
// gets the content of each tag
String email = c.getString(TAG_EMAIL);
String firstName = c.getString(TAG_FNAME);
String lastName = c.getString(TAG_LNAME);
String address = c.getString(TAG_ADDRESS);
String phoneNumber = c.getString(TAG_PHONE);
String city = c.getString(TAG_CITY);
String state = c.getString(TAG_STATE);
String zip = c.getString(TAG_ZIP);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EMAIL, email);
map.put(TAG_FNAME, firstName);
map.put(TAG_LNAME, lastName);
map.put(TAG_ADDRESS, address);
map.put(TAG_PHONE, phoneNumber);
map.put(TAG_CITY, city);
map.put(TAG_STATE, state);
map.put(TAG_ZIP, zip);
// adding HashList to ArrayList
mEmailList.add(map);
for (HashMap<String, String> maps : mEmailList){
for (Entry<String, String> mapEntry : maps.entrySet()){
String key = mapEntry.getKey();
String value = mapEntry.getValue();
if (value.equals(passedEmail)) {
Log.e("Is this email in the database?", value + " Is in the database!!!");
int index = map.get(key).indexOf(value);
Log.e("mEmailList: ", "" + mEmailList);
// String[] test = mEmailList.indexOf(value);
fullName = mEmailList.get(index).get(TAG_FNAME) +
" " +
mEmailList.get(index).get(TAG_LNAME);
mPhoneNumber = mEmailList.get(index).get(TAG_PHONE);
mAddress = mEmailList.get(index).get(TAG_ADDRESS) + " " +
mEmailList.get(index).get(TAG_CITY) + " " +
mEmailList.get(index).get(TAG_STATE) + " " +
mEmailList.get(index).get(TAG_ZIP);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It looks like you want the index within the list that contains a map that has a specific email address as one of the values. For that purpose you need to call indexOf on the list, and pass to it a Map.
Something like : mEmailList.indexOf(map).
What you are doing is searching for the index of the first occurrence of a sub-string within another String. That won't give you an index within the list.
In addition, it looks like you are mixing the code that creates the list of maps with the code that searches the list for a specific email.
You are getting -1 because of
test2.indexOf("v8")
The ArrayList test2 contains arrays String[], it doesn't containg "v8". test2, for example, contains { "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8" }, but not "v8".
Note: The methods String#indexOf() and ArrayList#indexOf() are different, so you should read their specification before using them.
I am trying to export the 4 columns with the below code.the last column organization is a List.
String appname = "abc";
String path = "//home/exportfile//";
String filename = path + "ApplicationExport-" + appname + ".txt";
String ret = "false";
QueryOptions ops = new QueryOptions();
Filter[] filters = new Filter[1];
filters[0] = Filter.eq("application.name", appname);
ops.add(filters);
List props = new ArrayList();
props.add("identity.name");
// Do search
Iterator it = context.search(Link.class, ops, props);
// Build file and export header row
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write("IdentityName,UserName,WorkforceID,Organization");
out.newLine();
// Iterate Search Results
if (it != null) {
while (it.hasNext()) {
// Get link and create object
Object[] record = it.next();
String identityName = (String) record[0];
Identity user = (Identity) context.getObject(Identity.class, identityName);
// Get Identity attributes for export
String workforceid = (String) user.getAttribute("workforceID");
// Get application attributes for export
String userid = "";
List links = user.getLinks();
if (links != null) {
Iterator lit = links.iterator();
while (lit.hasNext()) {
Link l = lit.next();
String lname = l.getApplicationName();
if (lname.equalsIgnoreCase(appname)) {
userid = (String) l.getAttribute("User Name");
List organizations = l.getAttribute("Organization");
StringBuilder sb = new StringBuilder();
String listItemsSeparator = ",";
for (Object organization : organizations) {
sb.append(organization.toString());
sb.append(listItemsSeparator);
}
org = sb.toString().trim();
}
}
}
// Output file
out.write(identityName + "," + userid + "," + workforceid + "," + org);
out.newLine();
out.flush();
}
ret = "true";
}
// Close file and return
out.close();
return ret;
the output of the above code will be.for ex:
IdentityName,UserName,WorkforceID,Organization
dthomas,dthomas001,12345,Finance,HR
How do i get the output in below fashion
IdentityName,UserName,WorkforceID,Organization
dthomas,dthomas001,12345,Finance
dthomas,dthomas001,12345,HR
what and where i need to change the code?
You'll have to write one line to the file for each organization. So, basically, do not concatenate all organizations for a user with the string builder and move the output statements into the for loop that iterates through the organizations.
But it's difficult to provide a working example, because you're code you've shown doesn't compile yet...
This should bring you somewhat closer to the solution:
if (links != null) {
Iterator lit = links.iterator();
while (lit.hasNext()) {
Link l = lit.next();
String lname = l.getApplicationName();
if (lname.equalsIgnoreCase(appname)) {
userid = (String) l.getAttribute("User Name");
List organizations = l.getAttribute("Organization");
for (Object organization : organizations) {
// Output file
out.write(identityName + "," + userid + "," + workforceid + "," + organization);
out.newLine();
out.flush();
}
}
}
}
Remove this innermost for block and associated variables:
StringBuilder sb = new StringBuilder();
for (Object organization : organizations)
{
sb.append(organization.toString());
sb.append(listItemsSeparator);
}
org = sb.toString().trim();
Move the declaration of organizations outside the if (it != null) { block:
// Get application attributes for export
String userid = "";
List organizations = null;
List links = user.getLinks();
if (it != null)
{
Iterator lit = links.iterator();
while (lit.hasNext())
{
Link l = lit.next();
String lname = l.getApplicationName();
if (lname.equalsIgnoreCase(appname))
{
userid = (String) l.getAttribute("User Name");
organizations = l.getAttribute("Organization");
And then change this file output code:
// Output file
out.write(identityName + "," + userid + "," + workforceid + "," + org);
out.newLine();
To this:
// Output file
for (Object organization : organizations)
{
out.write(identityName + "," + userid + "," + workforceid + "," + organization.toString());
out.newLine();
}