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 2 months ago.
Improve this question
I have a wrapped in class Marks HashMap which is subjectMark
public class Marks{
private final Map<String, Integer> subjectMark = new HashMap<>();
}
and I want somehow to add new maps and iterate over this HashMap in my general class RecordBook.
public class RecordBook {
private final Map<Integer, Marks> semesterSubjectMark = new HashMap<>();
public void addSemester(int semester, String subject, int mark){
//how to add such map - Map<semester, Map<subject, mark>>
//semesterSubjectMark.put(semester, Map<subject, mark>)
}
public void gpa(){
for(var semester : semesterSubjectMark.entrySet()){
//for(var subject : (inner map which wrapped in class Marks).entrySet()){
// ...
// }
}
}
}
I think that I should implement methods to add new maps like
public void addSubjectMark(String subject, int mark){
subjectMark.put(subject, mark);
}
in Marks. But how to iterate over all these maps?
I tried to iterate over with for-each, but it doesn't work for inner Map.
public class Marks {
private final Map<String, Integer> subjectMark = new HashMap<>();
public void addSubjectMark(String subject, int mark) {
subjectMark.put(subject, mark);
}
public Map<String, Integer> getSubjectMark() {
return subjectMark;
}
}
Above is Marks;
public class RecordBook {
private final Map<Integer, Marks> semesterSubjectMark = new HashMap<>();
public void addSemester(int semester, String subject, int mark) {
Marks marks = semesterSubjectMark.get(semester);
if (marks == null) {
marks = new Marks();
semesterSubjectMark.put(semester, marks);
}
marks.addSubjectMark(subject, mark);
}
public void gpa() {
int totalMark = 0;
int totalCredit = 0;
for (Map.Entry<Integer, Marks> entry : semesterSubjectMark.entrySet()) {
Marks marks = entry.getValue();
for (Map.Entry<String, Integer> entry1 : marks.getSubjectMark().entrySet()) {
String subject = entry1.getKey();
int mark = entry1.getValue();
int credit = 0;
if (subject.equals("Math")) {
credit = 2;
}
if (subject.equals("English")) {
credit = 1;
}
// It's something like above if's, but I don't want to write them all.
totalMark += mark * credit;
totalCredit += credit;
}
}
System.out.println("totalCredit:" + totalCredit);
System.out.println("totalCredit:" + totalCredit);
System.out.println("avg:" + totalMark / totalCredit);
}
}
Here u go brother, not sure if method GPA() is what u want, but that's how I sees it;
To iterate over the nested maps, you should retrieve appropriate subjectMark from the map entry:
public void gpa() {
for (var semester : semesterSubjectMark.entrySet()) {
// semester is Map.Entry<Integer, Marks>
for (var subject : semester.getValue().getSubjectMark().entrySet()) {
// subject is Map.Entry<String, Integer>
}
}
To add an entry to the outer map:
public void addSemester(int semester, String subject, int mark) {
semesterSubjectMark.computeIfAbsent(semester, (k) -> new Marks())
.getSubjectMark().put(subject, mark);
}
Related
Say I have the following classes:
class PersonWithFirstName {
String firstName;
}
class PersonWithFullName {
String fullName; // note assume this is not delimited in any way
}
class PersonWithFirstNameAndFullName {
String firstName;
List fullNames;
}
Now given a Map<Integer, PersonWithFirstName> and a Map<Integer, PersonWithFullName> where the key is the id (but the ids from the two maps are not coorelated), I want to write a function that returns PersonWithFirstNameAndFullName which for each firstName in Map<String, PersonWithFirstName>, finds any full names in the other map that begin with this firstName.
As an example:
Map<Integer, PersonWithFirstName> mapPersonsWithFirstName = new HashMap<>();
Map<Integer, PersonWithFulltName> mapPersonsWithFullName = new HashMap<>();
mapPersonsWithFirstName.set(1, new PersonWithFirstName("bob"));
mapPersonsWithFirstName.set(2, new PersonWithFirstName("alice"));
mapPersonsWithFullName.set(1, new PersonWithFullName("bobjohnson"));
mapPersonsWithFullName.set(2, new PersonWithFullName("bobjames"));
myFunction(mapPersonsWithFirstName, mapPersonsWithFullName)
/* should return
{
1: {
firstName: "bob"
fullNames: ["bobjohnson", "bobjames"]
},
2: {
firstName: "alice"
fullNames: []
}
}
*/
The only way I came up with is looping through the entryset of mapPersonsWithFirstName, and for each PersonWithFirstName doing another loop through mapPersonsWithFullName to find any PersonWithFullName.fullName that starts with PersonWithFirstName.firstName. This runs is exponential time, but I'm really thinking this can be solved in linear time. Any help is appreciated!
You could use TreeSet for ordering all your names and then just get desired subsequences (using tailSet and headSet methods):
private static List<PersonWithFirstNameAndFullName> myFunction(List<String> firstNames, List<String> fullNames) {
List<PersonWithFirstNameAndFullName> res = new ArrayList<>();
firstNames.sort(Comparator.reverseOrder());
NavigableSet<String> allNames = Stream.concat(firstNames.stream(), fullNames.stream()).collect(Collectors.toCollection(TreeSet::new));
for (String firstName : firstNames) {
final SortedSet<String> tail = allNames.tailSet(firstName, false);
allNames = new TreeSet<>(allNames.headSet(firstName));
res.add(new PersonWithFirstNameAndFullName(firstName, new ArrayList<>(tail)));
}
return res;
}
If the code above doesn't quite meet your requirements, you can change it.
But, in general, the main idea is to use TreeSet or TreeMap.
Update (to match the signature of your methods):
public static List<PersonWithFirstNameAndFullName> myFunction(Map<Integer, PersonWithFirstName> mapPersonsWithFirstName, Map<Integer, PersonWithFullName> mapPersonsWithFullName) {
return myFunction(mapPersonsWithFirstName.values().stream().map(PersonWithFirstName::getFirstName).collect(Collectors.toList()),
mapPersonsWithFullName.values().stream().map(PersonWithFullName::getFullName).collect(Collectors.toList()));
}
I think this way It is not exponential anymore:
public static void main(String[] args) {
Map<Integer, PersonWithFirstName> firstNames = new HashMap<>();
Map<Integer, PersonWithFullName> fullNames = new HashMap<>();
firstNames.put(1, new PersonWithFirstName("bob"));
firstNames.put(2, new PersonWithFirstName("alice"));
firstNames.put(3, new PersonWithFirstName("test1"));
firstNames.put(4, new PersonWithFirstName("test2"));
firstNames.put(5, new PersonWithFirstName("test3"));
fullNames.put(1, new PersonWithFullName("bobjohnson"));
fullNames.put(2, new PersonWithFullName("bobjames"));
fullNames.put(3, new PersonWithFullName("test1aaaa"));
fullNames.put(4, new PersonWithFullName("aliceSurname"));
Map<String, Set<String>> firstToFull = new HashMap<>();
List<String> firstNamesSorted = firstNames.values().stream().map(it -> it.firstName).sorted().collect(Collectors.toList());
List<String> fullNamesSorted = fullNames.values().stream().map(it -> it.fullName).sorted().collect(Collectors.toList());
int indexFirstName = 0;
int indexFullName = 0;
while (indexFirstName < firstNamesSorted.size() && indexFullName < fullNamesSorted.size()) {
String firstName = firstNamesSorted.get(indexFirstName);
String fullName = fullNamesSorted.get(indexFullName);
if (fullName.startsWith(firstName)) {
firstToFull.computeIfAbsent(firstName, n -> new HashSet<>())
.add(fullName);
indexFullName++;
} else {
if(compare(firstName, fullName) == 1) {
indexFullName++;
} else {
indexFirstName++;
}
}
}
int firstNamesSize = firstNamesSorted.size();
int i = 0;
while (firstToFull.size() < firstNamesSize) {
String name = firstNamesSorted.get(i);
firstToFull.computeIfAbsent(name, n -> new HashSet<>());
i++;
}
System.out.println(firstToFull);
}
private static int compare(String firstName, String fullName) {
String substring = fullName.substring(0, firstName.length());
return firstName.compareTo(substring);
}
I am working on a problem I came across in an interview.
Input contains Population|City|State|Interstates list
Output needs to be sorted in descending order by population first, then alphabetically by city and state, and then the interstates need to be sorted in ascending order too.
Sample input:
27|Chicago|Illinois|I-94;I-90;I-88;I-57;I-55
83|New York|New York|I-78;I-95;I-87;I-80
15|Phoenix|Arizona|I-10;I-17;I-8
15|Philadelphia|Pennsylvania|I-95;I-76
Sample output:
83
New York, New York
Interstates: I-78, I-80, I-87, I-95
27
Chicago, Illinois
Interstates: I-55, I-57, I-88, I-90, I-94
15
Philadelphia, Pennsylvania
Interstates: I-76, I-95
Phoenix, Arizona
Interstates: I-8, I-10, I-17
Here's my approach so far. I am currently stuck in the if block where I've added a comment. I am not sure if I am going in the right direction. I am looking for a hint to take the right approach here.
Scanner sc = new Scanner(System.in);
String line;
List<String> al = new ArrayList<>();
//Outer map sorts reverse by population, inner map1 sorts by city, inner
map2 sorts by state
Map<Integer, Map<String, Map<String, String>>> outerMap = new TreeMap<>
(Collections.reverseOrder());
Map<String, Map<String, String>> innerMap1 = new TreeMap<>();
Map<String, String> innerMap2 = new TreeMap<>();
while(sc.hasNextLine() && (line = sc.nextLine()).length()!=0) {
//Ignore if input contains this character
if(line.contains("#")) {
line = sc.nextLine();
}
al.add(line);
}
for(int i = 0; i < al.size(); i++) {
int outerMapKey = Integer.parseInt(al.get(i).split("\\|")[0]);
String innerMap1Key = al.get(i).split("\\|")[1];
String innerMap2Key = al.get(i).split("\\|")[2];
String value = al.get(i);
outerMap.get(outerMapKey);
if(outerMap.containsKey(outerMapKey)) {
innerMap1 = outerMap.get(outerMapKey);
/* Logic to put values in inner maps
This is going to get very convoluted, not sure if I have the
right approach
*/
}
else {
innerMap1 = new TreeMap<>();
innerMap2 = new TreeMap<>();
innerMap2.put(innerMap2Key, value);
innerMap1.put(innerMap1Key, innerMap2);
outerMap.put(outerMapKey, innerMap1);
}
}
Thank you for all your help so far. I am posting my code (working now) based on feedback here. Please take a look and suggest how it can be improved.
public static void main(String[] args) {
Map<String, List<PopulationByCityState>> map = readAndProcessInput();
printSortedOutput(map);
}
private static Map<String, List<PopulationByCityState>> readAndProcessInput() {
Map<String, List<PopulationByCityState>> map = readInput();
sortByPopulationCityAndState(map);
return map;
}
private static Map<String, List<PopulationByCityState>> readInput() {
System.out.println("Enter input:");
Scanner sc = new Scanner(System.in);
String line;
Map<String, List<PopulationByCityState>> map = new TreeMap<>(Collections.reverseOrder());
while (sc.hasNextLine() && (line = sc.nextLine()).length() != 0) {
if (line.contains("#")) {
line = sc.nextLine();
}
populateMap(line, map);
}
return map;
}
private static void populateMap(String line, Map<String, List<PopulationByCityState>> map) {
String[] s = line.split("\\|");
String[] is = s[3].split(";");
String key = s[0];
PopulationByCityState p = new PopulationByCityState();
p.setPopulation(Long.parseLong(s[0]));
p.setCity(s[1]);
p.setState(s[2]);
List<String> interstates = new ArrayList<>();
for (String aString : is) {
interstates.add(aString);
}
sortInterstates(interstates);
p.setInterstates(interstates);
if (map.containsKey(key)) {
map.get(key).add(p);
} else {
List<PopulationByCityState> al = new ArrayList<>();
al.add(p);
map.put(key, al);
}
}
private static void sortInterstates(List<String> interstates) {
Collections.sort(interstates, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
int n1 = Integer.parseInt(o1.split("-")[1]);
int n2 = Integer.parseInt(o2.split("-")[1]);
return n1 - n2;
}
});
}
private static void sortByPopulationCityAndState(Map<String, List<PopulationByCityState>> map) {
for (Map.Entry entry : map.entrySet()) {
List<PopulationByCityState> list = (List<PopulationByCityState>) entry.getValue();
Collections.sort(list, new Comparator<PopulationByCityState>() {
#Override
public int compare(PopulationByCityState o1, PopulationByCityState o2) {
int c;
c = (int) (o2.getPopulation() - o1.getPopulation());
if (c == 0) {
c = o1.getCity().compareTo(o2.getCity());
}
if (c == 0) {
c = o1.getState().compareTo(o2.getState());
}
return c;
}
});
}
}
private static void printSortedOutput(Map<String, List<PopulationByCityState>> map) {
for (Map.Entry<String, List<PopulationByCityState>> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println();
List<PopulationByCityState> list = entry.getValue();
for (PopulationByCityState p : list) {
System.out.println(p.getCity() + ", " + p.getState());
List<String> interstates = p.getInterstates();
System.out.print("Interstates: ");
int s = 0;
for (String is : interstates) {
s++;
System.out.print(is);
if (s != interstates.size()) {
System.out.print(", ");
}
}
System.out.println();
System.out.println();
}
}
}
Your approach relies on over complicated and not meaningful structure and also uses a Comparator that will only sort the first level of the map :
Map<Integer, Map<String, Map<String, String>>> outerMap = new TreeMap<>
(Collections.reverseOrder());
A finer approach could rely on using a class that represents each individual information that you need to represent a population for a state : PopulationForState
Here is a very simple representation of it (that is of course improvable but that should help you to understand the logic) :
public class PopulationForState{
private long population;
private String city;
private String state;
private List<String> interstates;
...
// getters
}
Add instances of them in a List and use a comparator that sorted them in descending order by population first, then alphabetically by city and state.
The interstates field may be sorted independently or directly during the sort of outer elements.
You could provide a sort method in PopulationForState, for example sortInnerStates() that sorts them in ascending order.
Personally, I would make it independently to keep the processing less coupled between.
So you could write something like :
List<PopulationForState> populationForStates = new ArrayList<>();
populationForStates.add(new PopulationForState(...));
populationForStates.add(new PopulationForState(...));
Collection.sort(populationForStates, Comparator.comparing(PopulationForState::population).reversed()
.thenComparing(PopulationForState::getCity)
.thenComparing(PopulationForState::getState);
populationForStates.stream()
.forEach(PopulationForState::sortInnerStates);
If you have a structure such the one posted in above post:
public class PopulationForState{
public long population;
public String city;
public String state;
public List<String> interstates;
//Do encapsulate
}
You can sort it with one comparator:
Collections.sort(populatisForStates, new Comparator<PopulationForState>(){
public int compare(PopulationForState first, PopulationForState scnd) {
int compare = first.population - scnd.population;
if(compare != 0) return compare;
compare = first.city.compareTo(scnd.city);
if(compare != 0) return compare;
return first.state.compareTo(scnd.state);
}
});
Sorting Interstates is similar and you just need to use Collections.sort(interstates) on each instance.
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 6 years ago.
Improve this question
I wrote a program which constituted by several class,but the calculation is too slow(Program in bold), I hope get my java program running on GPU to speed up the computation,or is there another way to speed up the running speed,How do I change my code?
Calculation of the program are as follows:
public class ComputeThreadPool {
public static double[][] distance = new double[40][8];
public static HashMap<String,Double> simMap = new HashMap<String,Double>();
static class WorkThread implements Runnable {
private Map<String, Double> testWordTFMap;
private Map<String, Double> trainWordTFMap;
private Map<String, double[]> words;
private String trainname;
public WorkThread(Map<String, Double> map1, Map<String, Double> map2, Map<String, double[]> words,String trainname) {
this.testWordTFMap = map1;
this.trainWordTFMap = map2;
this.words = words;
this.trainname=trainname;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
double mul = 0, testAbs = 0, trainAbs = 0;
WordsSimilarity computeS = new WordsSimilarity();
double wf = 0;
Set<Map.Entry<String, Double>> testWordTFMapSet = testWordTFMap.entrySet();
for (Iterator<Map.Entry<String, Double>> it = testWordTFMapSet.iterator(); it.hasNext(); ) {
Map.Entry<String, Double> me = it.next();
Set<Map.Entry<String, Double>> trainWordTFMapSet = trainWordTFMap.entrySet();
***for (Iterator<Map.Entry<String, Double>> it2 = trainWordTFMapSet.iterator(); it2.hasNext(); ) {
Map.Entry<String, Double> me2 = it2.next();
wf = computeS.similarity(me.getKey(), me2.getKey(), words);
if (wf > 0.45)
mul += wf * me.getValue() * me2.getValue();
}
}***
for (Iterator<Map.Entry<String, Double>> it3 = testWordTFMapSet.iterator(); it3.hasNext(); ) {
Map.Entry<String, Double> me3 = it3.next();
testAbs += me3.getValue() * me3.getValue();
}
testAbs = Math.sqrt(testAbs);
Set<Map.Entry<String, Double>> trainWordTFMapSet = trainWordTFMap.entrySet();
for (Iterator<Map.Entry<String, Double>> it4 = trainWordTFMapSet.iterator(); it4.hasNext(); ) {
Map.Entry<String, Double> me4 = it4.next();
trainAbs += me4.getValue() * me4.getValue();
}
trainAbs = Math.sqrt(trainAbs);
simMap.put(trainname,mul / (testAbs * trainAbs));
System.out.println(Thread.currentThread().getName() + " Start. " );
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}
private void processCommand() {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static HashMap<String,Double> main(Map<String, Double> testWordTFMap,Map<String, TreeMap<String, Double>> trainFileNameWordTFMap,Map<String, double[]> words) {
int num=0;
ExecutorService executor = Executors.newFixedThreadPool(6);
Set<Map.Entry<String,TreeMap<String,Double>>> trainFileNameWordTFMapSet = trainFileNameWordTFMap.entrySet();
for(Iterator<Map.Entry<String,TreeMap<String,Double>>> it = trainFileNameWordTFMapSet.iterator(); it.hasNext();){
Map.Entry<String, TreeMap<String,Double>> me = it.next();
num=num++;
Runnable worker = new WorkThread(testWordTFMap,me.getValue(),words,me.getKey());
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
return simMap;
}
}
wf is calculated as follows:
public static double similarity(String word1, String word2,Map<String, double[]> words) {
double[] count1=words.get(word1);
double[] count2=words.get(word2);
double sum=0;
double Abs1=0;
double Abs2=0;
if(count1 == null || count2 == null) {
return 0;
}
for (int c = 0; c < count1.length; c++) {
sum += count1[c] * count2[c];
Abs1 += count1[c] * count1[c];
Abs2 += count2[c] * count2[c];
}
return sum / (Abs1 * Abs2);
}
You would need to find an implementation of the JVM that runs on the GPU or a runtime environment/shell that targets the GPU in which you can run the standard JVM; but unless the JVM is built for the GPU you may or may not get performance gains.
However I would say, you should be able to find optimisations within the code first. Such as using enhanced for loops. Other than the compute word similarity there doesn't seem to much there that should be causing excessive run time.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to sort house numbers in my project. But I did not get exact logic for my problem.
The list is:
9-11, 9-01, 10-02, 10-01, 2-09, 3-88, 9-03
I need to sort the above list as:
2-09, 3-88, 9-01, 9-03, 9-11, 10-01, 10-02
I need the output like above.
Can any one help me in Java coding?
The logic is simple here:
209 < 388 < 901 < 902 < 911 < 1001 < 1002
One possible solution is:
String[] input = {"9-11", "9-01", "10-02", "10-01", "2-09", "3-88", "9-03"};
Map<Integer, String> map = new TreeMap<Integer, String>();
for (String s : input) {
map.put(Integer.valueOf(s.replace("-", "")), s);
}
TreeSet<Integer> set = new TreeSet<Integer>(map.keySet());
String[] output = new String[input.length];
int i = 0;
for (Integer key : set) {
output[i++] = map.get(key);
}
If you want to support more flexible formats, you can implement Comparable to define exactly comparisson rules. Let's take a look at modified example:
class HouseNumber implements Comparable<HouseNumber>{
private Integer house;
private Integer flat;
private HouseNumber(String s) {
String[] fields = s.split("-");
house = Integer.valueOf(fields[0]);
flat = Integer.valueOf(fields[1]);
}
#Override
public int compareTo(HouseNumber o) {
if (house.compareTo(o.house) == 0) {
return flat.compareTo(o.flat);
}
return house.compareTo(o.house);
}
}
String[] input = {"9-11", "9-01", "10-02", "10-01", "2-09", "3-88", "9-03"};
Map<HouseNumber, String> map = new TreeMap<HouseNumber, String>();
for (String s : input) {
map.put(new HouseNumber(s), s);
}
TreeSet<HouseNumber> set = new TreeSet<HouseNumber>(map.keySet());
String[] output = new String[input.length];
int i = 0;
for (HouseNumber key : set) {
output[i++] = map.get(key);
}
Simply remove "-" from the list
9-11, 9-01, 10-02, 10-01, 2-09, 3-88, 9-03
becomes
911, 901, 1002, 1001, 209, 388, 903
Sort
209, 388, 901, 903, 911, 1001, 1002
Place the "-" back, skipping 2 places from the back
2-09, 3-88, 9-01, 9-03, 9-11, 10-01, 10-02
Simple as that !
Do like this
Your Comparator
class SimpleComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
String [] o1sub = o1.split("-");
String [] o2sub = o2.split("-");
int value1 = Integer.parseInt(o1sub[0]);
int value2 = Integer.parseInt(o2sub[0]);
if(value1!=value2){
return new Integer (value1).compareTo(value2);
}
int value3 = Integer.parseInt(o1sub[1]);
int value4 = Integer.parseInt(o2sub[1]);
if(value3!=value4){
return new Integer(value3).compareTo(value4);
}
return 0;
}
}
Data
String [] array ={"9-11","9-01","10-02","10-01","2-09","3-88","9-03"};
Sorting
Arrays.sort(array,new SimpleComparator());
System.out.println(Arrays.toString(array));
OutPut
[2-09, 3-88, 9-01, 9-03, 9-11, 10-01, 10-02]
I have share you solved problem, May be it will help you to get exactly you want...
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class HouseNo {
public HouseNo(String house, String block) {
this.houseno = house;
this.blockno = block;
}
private String houseno;
private String blockno;
public String getHouseno() {
return houseno;
}
public void setHouseno(String houseno) {
this.houseno = houseno;
}
public String getBlockno() {
return blockno;
}
public void setBlockno(String blockno) {
this.blockno = blockno;
}
public static class SortByHouseNo implements Comparator<HouseNo> {
#Override
public int compare(HouseNo o1, HouseNo o2) {
Integer first = Integer.valueOf(o1.getHouseno());
Integer second = Integer.valueOf(o2.getHouseno());
Integer f1 = Integer.valueOf(o1.getBlockno());
Integer f2 = Integer.valueOf(o2.getBlockno());
if (first.compareTo(second) == 0) {
return f1.compareTo(f2);
}
return first.compareTo(second);
}
}
#Override
public String toString() {
return "House -> " + this.getHouseno() + "-" + this.getBlockno();
}
public static void main(String[] args) {
// Final
String houseList[] = { "9-11", "9-01", "10-02", "10-01", "2-09",
"3-88", "9-03", "9-3" };
HouseNo house = null;
ArrayList<HouseNo> sortedList = new ArrayList<>();
for (String string : houseList) {
String h = string.substring(0, string.indexOf('-'));
String b = string.substring(string.indexOf('-') + 1);
house = new HouseNo(h, b);
sortedList.add(house);
}
System.out.println("Before Sorting :: ");
for (HouseNo houseNo : sortedList) {
System.out.println(houseNo);
}
Collections.sort(sortedList, new SortByHouseNo());
System.out.println("\n\nAfter Sorting HouseNo :: ");
for (HouseNo houseNo : sortedList) {
System.out.println(houseNo);
}
}
}
Updated solution......
I have below five Integer variables and during the program, they are assigned some values randomly. I want to get the largest variable name but not the variable value. And I want to know if at least two of them have the same value. Please provide an example. Thank you.
int politics_counter = 0;
int economics_counter = 0;
int foreign_counter = 0;
int sport_counter = 0;
int weather_counter = 0;
And now for an answer (kind of)
public class MyThingie {
TreeMap<Integer, String> data = new TreeMap<Integer, String>();
public void doIt() {
...
insertElement("politics_counter", politics_counter);
insertElement("economics_counter", economics_counter);
insertElement("foreign_counter", foreign_counter);
insertElement("sport_counter", sport_counter);
insertElement("weather_counter", weather_counter);
System.out.println("Highest variable is "+data.lastEntry().getValue());
}
public void insertElement(String name, Integer i) {
if (data.get(i) == null) {
System.out.println("Element "+name+" has the name value as "+data.get(i));
}
else {
data.put(name,i);
}
}
}
and now for a more interesting answer:
public class BiggestFinder {
public void showBiggester(Object o) throws Exception {
TreeMap<Integer, String> data = new TreeMap<Integer, String)();
for (Field f : o.getDeclaredFields()) {
Object v = f.getValue(o);
if (v instanceof Integer) {
if (data.get(v)!=null) {
System.out.println("Value for "+f.getName()+" is the same as "+data.get(v));
}
else {
data.put((Integer)f.getValue(o), f.getName());
}
}
}
System.out.println("Largest is "+data.lastEntry().getValue());
}
}
which will interrogate an object and show the largest field, given that the object has members that are all Integers and that are all accessible to this method. There's a way to fudge that and improve it to make it more "robust".
As #Max suggested you can use a map for storing your variables and then manipulate the map for finding either biggest variable name or value.
// Initialize your map
HashMap<String, Integer> vars = new HashMap<String,Integer>();
// Inserting a variable
vars.put("politics_counter", new Integer(0));
// Looking for biggest variable
String biggestVar = "";
for (String key : vars.keySet()) {
if (key.length() > biggestVar.length)
biggestVar = key;
}