Calendar order in java [closed] - java

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 4 years ago.
Improve this question
public class FileDAO extends DaoBase implements ITreeDao {
File rootDirectory = null;
public FileDAO(File rootDirectory) {
if(!rootDirectory.exists()){
throw new IllegalArgumentException("Directory " + rootDirectory.getAbsolutePath() + " doesn't exist");
}
this.rootDirectory = rootDirectory;
}
protected ITreeNode readRoot(ITree tree) {
tree.setRoot(readNode(this.rootDirectory));
TreeSorter.sortById(tree.getRoot());
return tree.getRoot();
}
protected Set readChildren(ITreeNode parentNode) {
Set children = new HashSet();
File parentDir = (File) parentNode.getObject();
String[] files = parentDir.list();
if(files == null) return children;
for(int i=0; i<files.length; i++){
File childFile = new File(parentDir.getAbsolutePath() + File.separator + files[i]);
ITreeNode child = readNode(childFile);
child.setParentId(parentNode.getId());
if(!childFile.exists()) continue;
children.add(child);
}
// Sort here
TreeSorter.sortById(parentNode);
return children;
}
protected Set readGrandChildren(ITreeNode parentNode) {
Set grandChildren = new HashSet();
Iterator children = parentNode.getChildren().iterator();
while(children.hasNext()){
ITreeNode child = (ITreeNode) children.next();
grandChildren.addAll(readChildren(child));
}
return grandChildren;
}
protected ITreeNode readNode(File file){
if(!file.exists()) return null;
ITreeNode node = null;
String childType = file.isDirectory() ? "directory" : "file";
if(childType.equals("file")){
node = new TreeNode(file.getAbsolutePath(), "<a href=\"openPdf.jsp?fileName=" + file.getAbsolutePath() + "\" target=_blank>" + file.getName() + "</a>" , childType);
}else{
node = new TreeNode(file.getAbsolutePath(), file.getName() , childType);
}
node.setObject(file);
return node;
}
}
In this code am facing one issue at readGrandChildren() method. Like there I'm getting calendar months ascending order but I want to display calendar order like Jan,Feb,Mar.....Dec.
Please can anyone help me?
Thanks&Regards,
Venkat.
https://github.com/business-logic/br4j/blob/master/base/SharedComponents/Controls/src/com/jenkov/prizetags/tree/impl/FileDao2.java

use TreeSet, by implementing Comparator interface and providing reverse sorting logic and finally add all elements of HashSet to TreeSet using addAll() method of Collection interface.
// using Comparator constructor argument of TreeSet
TreeSet < String > ts = new TreeSet < String > (new Comparator < String > () {
#Override
public int compare(String o1, String o2) {
// reverse sorting logic
return o2.compareTo(o1);
}
});
// add HashSet elements to TreeSet
ts.addAll(grandChildren);
System.out.println("\n\n\nAfter Sorting : Descending order\n");
// Iterating using Iterator
Iterator < String > ascSorting = ts.iterator();
while (ascSorting.hasNext()) {
System.out.println(ascSorting.next());
}

Related

find the most and least used string in an ArrayList

I am having trouble finding the most and least used String in an ArrayList. The program should go through a file of Strings and count how many multiple strings there are in the list. Then print the least and most used name in the list. The ArrayList Part is finished. It is just finding the most and least common name I am having trouble with. I have no idea how to even start with it. This is what I have found online but it is not working.
Map<String, Integer> dogNames = new HashMap<>();
for (Dog dog : dogs) {
Integer value = dogNames.get(dog);
if (value == null) {
value = 0;
}
value++;
dogNames.put(dog.getName(), value);
}
int leastCommon = Integer.MAX_VALUE;
String leastCommonName = null;
for (String name : dogNames.keySet()) {
int value = dogNames.get(name);
if (value < leastCommon) {
leastCommon = value;
leastCommonName = name;
}
}
System.out.println("Least common (" + leastCommon + ") is " + leastCommonName);
The problem with your code seems to be in this line:
Integer value = dogNames.get(dog);
Your map holds dog names (String), but you are getting the entry for the Dog, which does not exist! Thus, value stays 0 even if you've seen that name before. If you fix this, you code should work.
Instead of your loop for searching the least common name, you could also define a custom Comparator based on the counts in the map and then use Collections.min and Collections.max:
Comparator<Dog> comp = new Comparator<Dog>() {
#Override
public int compare(Dog o1, Dog o2) {
return Integer.compare(dogNames.get(o1.getName()), dogNames.get(o2.getName()));
}
};
System.out.println("least " + Collections.min(dogs, comp));
System.out.println("most " + Collections.max(dogs, comp));
With Java 8, you can make it even shorter, using Comparator.comparing:
List<Dog> dogs = ...
Map<String, Integer> dogNames = new HashMap<>();
dogs.forEach(dog -> dogNames.put(dog.getName(), dogNames.getOrDefault(dog.getName(), 0) + 1));
Comparator<Dog> comp = Comparator.comparing(d -> dogNames.get(d.getName()));
System.out.println("least " + Collections.min(dogs, comp));
System.out.println("most " + Collections.max(dogs, comp));
Or even shorter, using Collections.frequency instead of building your own map, and using that to compare. Note, however, that this will be wasteful if the list is very long, since this will search the list each time anew instead of caching the counts in the map.
List<Dog> dogs = ...
Comparator<Dog> comp = Comparator.comparing(d -> Collections.frequency(dogs, d.getName()));
System.out.println("least " + Collections.min(dogs, comp));
System.out.println("most " + Collections.max(dogs, comp));
Your code should look something like this...
Map<String,int> frequencyOfDogNames = new HashMap<String,int>();
for(String dogName:dogNames) {
if(frequencyOfDogNames.contains(dogName)) {
continue;
}
frequencyOfDogNames.put(dogName, Collections.frequency(dogs, "dogName"));
}
This will give you the map of all the names with the occurrences.
Now we should loop thought the map to see which one are the max and min...
int leastCommon = Integer.MAX_VALUE;
int mostCommon = 0;
String leastCommonName, mostCommonName;
int occurrence;
for(String dogName: frequencyOfDogNames.keySet()) {
occurrence = frequencyOfDogNames.get(dogName);
if(leastCommon > occurrence){
leastCommon = occurrence;
leastCommonName = dogName;
}
if(mostCommon < occurrence){
mostCommon = occurrence;
mostCommonName = dogName;
}
}

ArrayList object sorting by time property [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have two classes, MarathonAdmin and Runner.
I want to sort list (runners) holding objects of Runner class. I have done all
the coding up to the method sortRunnerList, which says sort the list. I have created
a compareTo method in Runner class and when I compare objects of Runner, they pick the default time values not the ones which I have assigned to objects generating random numbers (done in MarathonAdmin class).
Can someone help with this issue?
class Marathon
import java.util.*;
import java.io.*;
import ou.*;
import java.util.Random;
public class MarathonAdmin
{
// instance variables - replace the example below with your own
private List<Runner> runners;
private String ageGroup;
private String age;
private Random randomNumber;
private String result;
String ageRunner;
String ageGrouprunners;
Scanner lineScanner;
int ans ;
Runner runnerobj = new Runner();
Runner obj2 = new Runner();
public MarathonAdmin()
{
runners = new ArrayList<>();
}
public void readInRunners(){
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
String nameRunner;
BufferedReader bufferedFileReader = null;
try
{
bufferedFileReader = new BufferedReader(new FileReader(aFile));
String currentLine = bufferedFileReader.readLine();
while ( currentLine != null){
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
nameRunner = lineScanner.next();
ageRunner = lineScanner.next();
if (Integer.parseInt(ageRunner) < 18)
{
result = "junior";
System.out.println(currentLine +" category" + " : Junior");
}
if (Integer.parseInt(ageRunner) > 55)
{
result = "senior";
System.out.println(currentLine +" category"+ " : Senior");
}
if (Integer.parseInt(ageRunner) > 18 && Integer.parseInt(ageRunner) < 55)
{
result = "standard";
System.out.println(currentLine +" category"+ " : Standard");
}
ageGrouprunners = result;
Runner runnerobj = new Runner();
runnerobj.setName(nameRunner);
runnerobj.setAgeGroup(ageGrouprunners);
System.out.println(runnerobj); //rough test
runners.add(runnerobj);
currentLine = bufferedFileReader.readLine();
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
public void runMarathon(){
int size = runners.size();
// for ( int runnersIndex = 0; runnersIndex <= size; runnersIndex ++ ){
for( Runner nameRunner : runners){
this.randomNumber = new Random();
ans = randomNumber.nextInt(190 - 80 +1 ) + 90 ;
System.out.println(ans);
nameRunner.setTime(ans);
}
}
public void sortRunnerList(){
for(Runner nameRunner : runners){
int time = nameRunner.getTime();
System.out.println(time);
Runner obj = new Runner();
obj.setTime(ans);
int res = nameRunner.compareTo(obj);
System.out.println(res);
}
}
}
//(This is method of class Runner)
Class Runner
Method compareTo()
#Override
public int compareTo(Runner anotherRunner)
{
return this.getTime()-(anotherRunner.getTime());
}
Try replacing
return this.getTime()-(anotherRunner.getTime());
with
return Integer.valueOf(this.getTime()).compareTo(anotherRunner.getTime());

ArrayList as a Value to HashMap returns only last element of ArrayList

Please see the below code-
Map<DateTime, ArrayList<ElementInformationBean>> mapTithi = new HashMap<DateTime, ArrayList<ElementInformationBean>>();
List<ElementInformationBean> lstTime = null;
ElementInformationBean curntTithi = null;
ElementInformationBean nextTithi = null;
for (int i = 0; i < lstNakstra.size()-1; i++) {
lstTime = new ArrayList<ElementInformationBean>();
curntTithi = lstNakstra.get(i);
nextTithi = lstNakstra.get(i+1);
if(curntTithi.getStartTime().toDateMidnight().equals(nextTithi.getStartTime().toDateMidnight()))
{
lstTime.add(curntTithi);
lstTime.add(nextTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
} else {
lstTime.add(curntTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
}
}
For Printing
for (Map.Entry<DateTime, ArrayList<PanchangaElementInformationBean>> entry : mapTithi.entrySet()) {
DateTime key = entry.getKey();
ArrayList<PanchangaElementInformationBean> values = entry.getValue();
System.out.println("Key = " + key);
for (PanchangaElementInformationBean p: values) {
System.out.print("Values = " + p.getStartTime() + "n");
}
}
I am trying to use the HashMap; Key as dateTime and Value as List. However it always returns when I am iterating and printing the value.
Thanks
Kumar Shorav
Initialize lstTime outside the loop.
Try this code :
Map<DateTime, ArrayList<ElementInformationBean>> mapTithi = new HashMap<DateTime, ArrayList<ElementInformationBean>>();
// Intialize here
List<ElementInformationBean> lstTime = new ArrayList<ElementInformationBean>();
ElementInformationBean curntTithi = null;
ElementInformationBean nextTithi = null;
for (int i = 0; i < lstNakstra.size()-1; i++) {
curntTithi = lstNakstra.get(i);
nextTithi = lstNakstra.get(i+1);
if(curntTithi.getStartTime().toDateMidnight().equals(nextTithi.getStartTime().toDateMidnight()))
{
lstTime.add(curntTithi);
lstTime.add(nextTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
} else {
lstTime.add(curntTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
}
}
On your Getters and Setters of the PanchangaElementInformationBean class change the data type from Date to ArrayList<Date> and add that setStartTime to as bellow so you can get all values from it.
private ArrayList<Date> startTime;
public ArrayList<Date> getStartTime() {
return startTime;
}
public void setStartTime(Date item) {
if (startTime == null) {
startTime = new ArrayList<Date>();
}
this.startTime.add(item);
}
So while you iterate you can get all the values from the ArrayList
And add this on the main printing for loop to print individual Date from ArrayList
for (Date startTime : p.getStartTime()) {
System.out.println(startTime);
}
And Initialize lstTime = new ArrayList<ElementInformationBean>(); on above the For Loop so that you can add many elements are else it will add only one for loop instance value repeatedly to the list.
If you want to accumulate elements in a list used as value of a map, you have to use this approach:
List<...> list = map.get( key );
if( null == list ) {
list = new ...;
map.put( key, list );
}
list.add( ... );

To add an element to arraylist [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
public class Person {
private String name;
private boolean adopted;
private String parent;
private List<String> children;
public Person(String Aname) {
name = Aname;
children = new ArrayList<String>();
adopted = false;
}
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(name)
&& children.size() <= 10) {
person.parent = name;
// System.out.println(parent);
// children=person.name;
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
// System.out.println(children);
adopted = true;
}
}
public void setName(String name) {
this.name = name;
}
public void disown(Person person) {
}
public String toString() {
if (children.size() == 0 && parent == null) {
return name + " Parent: No parent. Children: No children ";
} else if (children.size() == 0) {
return name + " Parent: " + parent + " Children: No children";
} else if (parent == null) {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: No Parent " + "Children: " + list;
} else {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
}
}
}
In this I am trying to add person.name to arraylist children but I am not able to add. I am initialyzing the list then adding a name to the list.I am using adopt method to add children to the list. Please tell what am I doing wrong here.
The properties are private, please put setters and getters and then try to access to the getName() property.
The following code is incorrect:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
Each time you call Adopt(person) you add that child instead of all the children in the list.
Try using:
children.add(person.name);
EDIT:
Ok, the above is correct, but cristobal de Leon's answer is the explanation to what you're experiencing.
I'm pretty sure the problem is that after you create the new ArrayList(); you never assign any value to the list, so when you iterate based on children.size(), you will always iterate from 0 to 0 and never add any children in the next snippet:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
As per #summerbulb suggestion: person.name should be adopted by the current this so you should just do
children.add(person.name)
Also, at the end of the adopt method, I think you want to mark person (the parameter) as adopted and not this (the person adopting), so you may change
person.adopted=true;
instead of just adopted=true;
The number of items in you arraylist "children" is 0.
Look at this part code:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
for every object in children you will set the same name.
So you will set the name 0 times. That means there also won't be any output.
I think you need an array with al the persons you create in you main.
Change the adopt code to this:
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(this.name)) {
person.parent = name;
children.add(person.name);
person.adopted = true;
}
}
Make getters for your atributes or make them public like this:
public String name;
In your main:
Person[] persons = new Person[5];
persons[0] = new Person("Dude");
persons[1] = new Person("Dude's child");
persons[0].adopt(persons[1]);
Check your toString method. I am not sure if all children are printed. E.g. look at the case in which parent is not NULL and children.size() > 0
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
Here you are iterating over all children, take the name of the last children in the list and return it together with the parents name.
Besides: please check if children can also be of class Person

How to create an array in recursive function in java

I have a recursive method that prints out the values in command line. I need to create a temp array with the result an display it using Swing. how do I create the array and store the values each time it loops ?
static void listSnapshots(VirtualMachine vm)
{
if(vm == null)
{
JOptionPane.showMessageDialog(null, "Please make sure you selected existing vm");
return;
}
VirtualMachineSnapshotInfo snapInfo = vm.getSnapshot();
VirtualMachineSnapshotTree[] snapTree = snapInfo.getRootSnapshotList();
printSnapshots(snapTree);
}
static void printSnapshots(VirtualMachineSnapshotTree[] snapTree)
{
VirtualMachineSnapshotTree node;
VirtualMachineSnapshotTree[] childTree;
for(int i=0; snapTree!=null && i < snapTree.length; i++)
{
node = snapTree[i];
System.out.println("Snapshot name: " + node.getName());
JOptionPane.showMessageDialog(null, "Snapshot name: " + node.getName());
childTree = node.getChildSnapshotList();
if(childTree != null)
{
printSnapshots(childTree);
}
}//end of for
so instead of JOptionPane I have only onew window with the list of names and can reuse later.
A general tactic for building something recursively is to use a Collecting Parameter.
This can be applied in your case by:
static List<String> listSnapshotNames(VirtualMachineSnapshotTree[] snapTree) {
ArrayList<String> result = new ArrayList<String>();
collectSnapshots(snapTree, result);
return result;
}
static void collectSnapshots(VirtualMachineSnapshotTree[] snapTree, List<String> names)
{
VirtualMachineSnapshotTree node;
VirtualMachineSnapshotTree[] childTree;
for(int i=0; snapTree!=null && i < snapTree.length; i++)
{
node = snapTree[i];
names.add(node.getName());
childTree = node.getChildSnapshotList();
if(childTree != null)
{
collectSnapshots(childTree, names);
}
}//end of for
}
Of course, if you really want it in an array, you can convert it afterwards:
static String[] getSnapshotNames(VirtualMachineSnapshotTree[] snapTree) {
List<String> result = listSnapshotNames(snapTree);
return result.toArray(new String[0]);
}
With an unknown size, arrays are painful, so a List works better for this.

Categories