i want to convert the instance of class which is in ArrayList to toString i have here my code
User class:
public class User {
// ...
public void setName(String name) {
this.fullname = name;
}
#Override
public String toString() {
return this.fullname;
}
public ArrayList<User> getTheLikers() {
ArrayList<User> user = new ArrayList<>();
user.add(this);
return user;
}
Post class:
public class Post {
public ArrayList<User> getLikers() {
User a = new User();
ArrayList<User> b = a.getTheLikers();
return b;
}
and here is the code where i should get the getLikers()
while(rs.next()) {
User a = new User();
Post b = new Post();
String name = rs.getString("people_who_like");
a.setName(name);
ArrayList c;
c = b.getLikers();
String liker = c.toString();
p.addElement(liker);
}
i have already convert it to toString as you can see.. but it shows that i have display my value but it is in null
To convert ArrayList into a String. That is specifically what the question says.
ArrayList c;
c = b.getLikers();
String liker = "";
for (String s : c){
liker += s + "\t";
}
When using Java 8 you can use String#join for this:
String liker = String.join(", ", c);
or the Stream API:
String liker = c.stream().collect(Collectors.joining(", "));
Pre Java 8 you have use e.g. Guava for this or write our own function
public static String listToString(final List<String> list) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < list.size() - 1; i++) {
result.append(list.get(i));
result.append(", ");
}
result.append(list.get(list.size() - 1));
return result.toString();
}
Even the list having the method List.toString() where u can get list into the String format.
how ever here the one thing that u can use your list to convert into the string.
Use the static variable for the list.
public class MainClass {
static ArrayList<String> arrayList = new ArrayList<String>();
public static void main(String args[]) {
arrayList.add("Krish");
arrayList.add("Krish1");
arrayList.add("Krish2");
arrayList.add("Krish3");
arrayList.add("Krish4");
System.out.println(arrayList.toString());
}
}
Similar u can use tostring method like this. if u using just arraylist then it will give out put in string format.
other way to do this.
public static String arrayliststring(ArrayList arrayList) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < arrayList.size(); i++) {
buffer.append(arrayList.get(i).toString() + " ");
}
return buffer.toString();
}
hope this helps and for java 8 as ifloop said that is correct.
Related
How to split a type of car and color that user provides as input.
Input format is:
<Type>#<Color>
Output will show how many type of car that has the same color
input example:
how many cars : 10
sedan#red
truck#yellow
van#white
suv#black
sedan#black
roadster#red
suv#gray
coupe#gray
minivan#white
truck#red
output has to be sort in alphabetical
black 2
gray 2
red 3
white 2
yellow 1
Tried a sample code, still not done, but where kinda struggle about how to split the array T^T
Class1:
public class Class1 {
private String type ;
private String color;
private String format;
public Class1() {
this.type = "";
this.color = "";
this.format = "";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public void split () {
String part[] = format.split("#");
setType(part[0]);
setColor(part[1]); // i don't know if this will work or not..
}
}
Class2:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Class2 {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
int n ;
String format ;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
Class1 [] dataArray = new Class1[n] ;
Class1 data = new Class1();
for(int a = 0 ; a <= dataArray.length ; a++) {
dataArray[a] = data;
data.setFormat(br.readLine());
data.split();
data.getType();
data.getColor();
}
}
}
Coding is still not completed and still don't know how to split the array. Please help me solve this!
Change your for loop from this:
for(int a = 0 ; a <= dataArray.length ; a++) {
dataArray[a] = data;
data.setFormat(br.readLine());
data.split();
data.getType();
data.getColor();
}
to this:
for(int a = 0 ; a < dataArray.length ; a++) {
Class1 data = new Class1();
dataArray[a] = data;
data.setFormat(br.readLine());
data.split();
data.getType();
data.getColor();
}
The two important changes are:
You should only loop while a < dataArray.length, otherwise
you'll get an ArrayIndexOutOfBoundsException when a == dataArray.length.
You need to create a new instance of Class1 each time you read in
a new line, and store in position a of your dataArray
Other than this it looks fine. Obviously there are some quibbles in your design - maybe setFormat should call split, rather than requiring a separate call? - but you should now be able to iterate over dataArray and count colours, probably using a Map<String, Integer>
Initialize the new object Class1 data = new Class1(); inside the for-loop, rather than outside of it as otherwise it will be overridden every time the loop runs.
Also iterate through a < dataArray.length instead of a <= dataArray.length.
I have added the groupingBy to get the count grouped by the the color name. Then I sorted the entrySet of the resulting Map<String, Integer> and printed out the contents.
I have achieved the expected output without modifying your code too much.
public static void main(String[] args){
try{
int numberOfCars;
String format ;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
numberOfCars = Integer.parseInt(br.readLine());
Class1 [] dataArray = new Class1[numberOfCars] ;
for(int a = 0 ; a < dataArray.length ; a++) {
//Initializing new instance everytime
Class1 data = new Class1();
data.setFormat(br.readLine());
data.split();
dataArray[a] = data;
}
//Creating a Stream of Class1 objects
Arrays.stream(dataArray)
.collect(Collectors.groupingBy(car -> car.getColor(), Collectors.counting()))
.entrySet() //Getting entries from Map
.stream() //sorting after the Map is created to preserve the sorted order
.sorted(Comparator.comparing(entry -> entry.getKey())) //Sorting by key, that is the Color property of Class1
.forEach((entry) -> System.out.println(entry.getKey() + " "+ entry.getValue()));
}catch (NumberFormatException | IOException | ArrayIndexOutOfBoundsException e) {
System.out.println("Error occurred try again");
e.printStackTrace();
}
}
I'm a beginner when it comes to Java and I'm trying to pull these values vertically and store them in a data type with their reference. So "A" would have 1,8,7,6 mapped to it and the dates in front would be excluded as well. The csv file is below.
10/1/14, A,B,C,D,E,F,G,H
10/2/14, 1,2,3,4,5,6,7,8
10/3/14, 8,1,2,3,4,5,6,7
10/4/14, 7,8,1,2,3,4,5,6
10/5/14, 6,7,8,1,2,3,4,5
Here is my code. So far I've been able to grab the rows individually, but I'm I don't know how to add them to a data structure. This would return >> C3218
class Main {
public static void main(String[] args) {
Read r = new Read();
r.openFile();
r.readFile();
r.closeFile();
}
}
import java.io.*;
import java.util.*;
public class Read {
private Scanner x;
public void openFile() {
try {
x = new Scanner(new File("test.csv"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile() {
while(x.hasNext()){
String a = x.next();
String[] values = a.split(",");
System.out.printf(values[3]); // gets line
}
}
public void closeFile() {
x.close();
}
}
Java is an Object Oriented programming language. I'm going to assume that what you call "data structures" are Objects in Java parlance. For example (and these are just examples, not something you specifically could use for your situation), if I want to represent a person, I might have something like this
public interface Person{
String getName();
Date getBirthDate();
}
public class GenericPerson implements Person{
private final String name;
private final Date bdate;
public GenericPerson(String fullName, Date birthdate){
name = fullName;
bdate = birthdate;
}
#Override
public String getName() {
return name;
}
#Override
public Date getBirthDate() {
return bdate;
}
}
Pretty sparse, but I'm just trying to show some basic concepts.
You asked
I don't know how to add them to a data structure.
In my example, you would instantiate a GenericPerson
Person p = new GenericPerson(name,date);
Of course, you'll need the name and date variables. That's where the parsing the file comes in. So if I had a file of the form
George Costanza,5/4/1956
Cosmo Kramer,12/12/1960
Jerry Seinfeld,1/2/1959
Then in my code to parse the file I might have
String line = scanner.next();
String[] values = line.split(",");
Person p = new GenericPerson(values[0],getDateFormatter().parse(values[1]));
So you create your Object type, defining what fields you want it to have. And then populate them via a constructor or setter methods. An example of setter methods would be if I modified the GenericPerson like this
public class GenericPerson implements Person{
private String name;
private Date bdate;
public void setName(String n){
name = n;
}
public void setBirthDate(Date d){
bdate = d;
}
#Override
public String getName() {
return name;
}
#Override
public Date getBirthDate() {
return bdate;
}
}
Now I would need to call those to set the values in the Object.
For your case, you'll need to define some Object type that the data is meant to define. The type will have fields like the GenericPerson and you need to have setter methods or a constructor that takes arguments corresponding to the fields.
I highly recommend following the online tutorial for java beginners.
It took me 30 minutes just to get your code to compile and run correctly.
I used a List of a Column class that I created. The Column class contains the name of the column and the values in that CSV column.
The test.csv file is in the same directory as the Java class.
Here's the results.
A: 1, 8, 7, 6
B: 2, 1, 8, 7
C: 3, 2, 1, 8
D: 4, 3, 2, 1
E: 5, 4, 3, 2
F: 6, 5, 4, 3
G: 7, 6, 5, 4
H: 8, 7, 6, 5
And here's the code.
package com.ggl.testing;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CSVColumns implements Runnable {
public static void main(String[] args) {
new CSVColumns().run();
}
#Override
public void run() {
Scanner scanner = openFile();
if (scanner != null) {
readFile(scanner);
closeFile(scanner);
}
}
private Scanner openFile() {
String fileString = "test.csv";
return new Scanner(getClass().getResourceAsStream(fileString));
}
private void readFile(Scanner scanner) {
List<Column> columnList = new ArrayList<>();
String a = scanner.nextLine();
a = a.replace(" ", "");
String[] values = a.split(",");
for (int i = 1; i < values.length; i++) {
Column column = new Column(values[i]);
columnList.add(column);
}
while (scanner.hasNext()) {
a = scanner.nextLine();
a = a.replace(" ", "");
values = a.split(",");
for (int i = 0; i < columnList.size(); i++) {
Column column = columnList.get(i);
column.addValue(Integer.valueOf(values[i + 1]));
}
}
for (int i = 0; i < columnList.size(); i++) {
System.out.println(columnList.get(i));
}
}
private void closeFile(Scanner scanner) {
scanner.close();
}
public class Column {
private List<Integer> values;
private final String name;
public Column(String name) {
this.name = name;
this.values = new ArrayList<>();
}
public List<Integer> getValues() {
return values;
}
public void addValue(int value) {
this.values.add(Integer.valueOf(value));
}
public String getName() {
return name;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(": ");
for (int i = 0; i < values.size(); i++) {
int value = values.get(i);
builder.append(value);
if (i < (values.size() - 1)) {
builder.append(", ");
}
}
return builder.toString();
}
}
}
Using LinkedHashMap to store header(as Keys). LinkedHashMap preserves the insertion-order:
public void readFile() {
Map<String, String> map = new LinkedHashMap<String, String>();
boolean setInitValues = true, setKeys = true;
String[] keys = null;
while (x.hasNext()) {
String a = x.nextLine();
String[] values = a.split(",");
if (setKeys) { // set keys
keys = Arrays.copyOfRange(values, 1, values.length);
setKeys = false;
} else {
if (setInitValues) { // set initial values
for (int i = 1; i < values.length; i++)
map.put(keys[i - 1], values[i].trim());
setInitValues = false;
} else
// continue appending values
for (int i = 1; i < values.length; i++)
map.put(keys[i - 1],
map.get(keys[i - 1]).concat(values[i].trim()));
}
}
printMap(map); // print what you got
}
void printMap(Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet())
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
Output :
Key : A Value : 1876
Key : B Value : 2187
Key : C Value : 3218
Key : D Value : 4321
Key : E Value : 5432
Key : F Value : 6543
Key : G Value : 7654
Key : H Value : 8765
Hi guys I have been making a test class for my word puzzle game and the out put is printing the objects reference number to the object. Anyone got the solution to print the return statement of the object.
Output:
Generator stats: word-puzzles generated from words of length 3
Puzzle.WordPuzzleGenerator#c68c3Puzzle.WordPuzzleGenerator#b2002fPuzzle.WordPuzzleGenerator#2a4983Puzzle.WordPuzzleGenerator#406199Puzzle.WordPuzzleGenerator#c7b00cPuzzle.WordPuzzleGenerator#1f6f296Puzzle.WordPuzzleGenerator#1df5a8fPuzzle.WordPuzzleGenerator#b2a2d8Puzzle.WordPuzzleGenerator#1e13d52Puzzle.WordPuzzleGenerator#80fa6f
Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
int sizeTest1 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest1);
for (int i = 0; i < 10; i++) {
WordPuzzleGenerator puzzle = new WordPuzzleGenerator(sizeTest1);
System.out.print(puzzle);
}
int sizeTest2 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest2);
for (int i = 0; i < 10; i++) {
new WordPuzzleGenerator(sizeTest2);
}
}
}
Main program:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public WordPuzzleGenerator(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord) && !puzzleListY.contains(randomXWord)) {
finished = false;
break;
}
puzzleListX.add(randomXWord);
}
}
toString(puzzleListX, puzzleListY);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
public static String toString(ArrayList<String> ArrayList1, ArrayList<String> ArrayList2){
StringBuilder group1 = new StringBuilder();
for (int i = 0; i < ArrayList1.size(); i++) {
group1.append(ArrayList1.get(i) + " ");
}
String wordsInString1 = group1.toString();
StringBuilder group2 = new StringBuilder();
for (int i = 0; i < ArrayList2.size(); i++) {
group2.append(ArrayList2.get(i) + " ");
}
String wordsInString2 = group2.toString();
return String.format("\t( %s) ( %s)", wordsInString1, wordsInString2);
}
}
Your WordPuzzleGenerator class does not override Object's toString. Instead it contains a static toString method with a different signature.
You need a method of this signature in your WordPuzzleGenerator class :
#Override
public String toString()
{
...
}
After taking another look, it appers your WordPuzzleGenerator has only static methods and no instance members, so it's unclear what you expect toString to return, or in other words - it's not clear what System.out.print(puzzle); is expected to print.
EDIT:
If you want toString() to print the Lists created in your constructor, you should make them instance members :
ArrayList<String> puzzleListY;
ArrayList<String> puzzleListX;
public WordPuzzleGenerator(int size) throws FileNotFoundException {
puzzleListY = new ArrayList<String>();
puzzleListX = new ArrayList<String>();
...
}
Then you can override toString like this :
#Override
public String toString()
{
return WordPuzzleGenerator.toString (puzzleListX,puzzleListY);
}
you'll have to override the toString method of your objects, since your object inheris from java object
#Override
public String toString(){
\\mystring build up...
return mystring;
notice the override annotation, thats what does the trick ;)
happy coding!
try to override 'toString' method in your class as follows:
#Override
public String toString()
{
//your code
}
Im having a class Woning (house) and a subclass KoopWoning (buyable House) and a subclass HuurWoning (rentable House). KoopWoning and Huurwoning extend Woning. HuurWoning is just a Woning, whereas KoopWoning has an extra variable energylevel. KoopWoning has also a function getEnergylevel, which returns the energylevel of the KoopWoning. I also have a class Portefeuille which has an arraylist of Woningen.
Im reading all Woningen in a Portefeuille from a textfile. In a 5th class, I want to be able to sort the ArrayList of Woningen of Portefeuille (from the textfile). I have a function woningenTot(int maxprijs) which returns an ArrayList with all the Woningen that fullfil the requirement (having a price below maxprijs). These Woningen I want to print on the screen.
The problem is as follows:
It can be possible that there is also a KoopWoning in the file. In that case I also want to be able to sort on energylevel. However, I can't sort on the energylevels. I can't call the function getEnergylevel because it's an ArrayList, and Woning doesn't contain the function getEnergylevel.
So how can I solve this? If it's too vague, I could include the code, however it's quite big :O
Any help is appreciated; i have spent a couple of hours on this program, from which at least 1.5 hours on this problem alone :(
EDIT: Here is the code for class KoopWoning
public class KoopWoning extends Woning implements EnergiepeilWoning {
private char energiepeil;
public KoopWoning (Adres adres, int kamers, int vraagPrijs, char energiepeil) {
super(adres, kamers, vraagPrijs);
this.energiepeil = energiepeil;
}
public char getEnergiepeil () {
return energiepeil;
}
public boolean compareEnergiepeil (Object other) {
boolean res = false;
if (other instanceof KoopWoning) {
KoopWoning that = (KoopWoning) other;
res = (this.getEnergiepeil() == that.getEnergiepeil());
}
return res;
}
public String toString () {
String res = adres + ", " + kamers + " kamers, prijs " + prijs + ", energiepeil " + energiepeil;
return res;
}
And here is the code for class Woning
public class Woning {
protected int kamers;
protected int prijs;
protected Adres adres;
protected String tag;
public Woning (Adres adres, int kamers, int prijs) {
this.adres = adres;
this.kamers = kamers;
this.prijs = prijs;
}
public String toString () {
String res = adres + ", " + kamers + " kamers, prijs " + prijs;
return res;
}
public void setTag (String tag) {
this.tag = tag;
}
public String getTag () {
return tag;
}
public boolean kostHooguit (int maxprijs) {
return (prijs <= maxprijs);
}
public boolean equals (Object other) {
boolean res = false;
if (other instanceof Woning) {
Woning that = (Woning) other;
if (this.adres.equals(that.adres))
res = true;
}
return res;
}
public static Woning read (Scanner sc) {
try {
Adres adress = Adres.read(sc);
int kamer = sc.nextInt();
sc.next();
sc.next();
int prijs = sc.nextInt();
String check = sc.next();
if (check.equals("energiepeil")) {
char peil = sc.next().charAt(0);
KoopWoning kwoning = new KoopWoning (adress, kamer, prijs, peil);
return kwoning;
}
else {
Woning woning = new Woning (adress, kamer, prijs);
return woning;
}
}
catch (Exception e) {
System.out.println("Woning: Exception is caught");
System.out.println(e.getMessage());
Adres adress = new Adres ("", "", "", "");
Woning woning = new Woning (adress, 0, 0);
return woning;
}
}
}
And lastly, the code for the class Portefeuille
public class Portefeuille {
private ArrayList<Woning> woninglijst;
public Portefeuille () {
woninglijst = new ArrayList<Woning>();
}
public void voegToe (Woning woning) {
if (!woninglijst.contains(woning))
woninglijst.add(woning);
}
public ArrayList<Woning> woningenTot (int maxprijs) {
ArrayList<Woning> woninglijst2 = new ArrayList<Woning>();
for (int i = 0; i < woninglijst.size(); i++) {
if(woninglijst.get(i).kostHooguit(maxprijs))
woninglijst2.add(woninglijst.get(i));
}
return woninglijst2;
}
public String toStringExt () {
String res = "[";
for (int i = 0; i < woninglijst.size(); i++)
res = res + woninglijst.get(i).toString() + "; ";
if (woninglijst.size() != 0)
res = res.substring (0, res.length() - 2);
res = res + "]";
return res;
}
public String toString () {
String res = "";
for (int i = 0; i < woninglijst.size(); i++)
res = woninglijst.get(i).toString2();
return res;
}
public boolean equals (Object other) {
boolean res = false;
if (other instanceof Portefeuille) {
Portefeuille that = (Portefeuille) other;
if (this.woninglijst.size() == that.woninglijst.size()) {
int i = 0;
while (i < this.woninglijst.size() && this.woninglijst.get(i).equals(that.woninglijst.get(i)))
i = i + 1;
res = (i == this.woninglijst.size());
}
}
return res;
}
public static Portefeuille read (String infile) {
try {
Scanner sc = new Scanner (new File(infile));
ArrayList<Woning> wlijst = new ArrayList<Woning>();
Portefeuille p = new Portefeuille();
int woningen = sc.nextInt();
int i = 0;
while (i < woningen) {
sc.nextLine();
String tag = sc.nextLine();
wlijst.add(Woning.read(sc));
p.voegToe(wlijst.get(i));
i++;
}
sc.close();
return p;
}
catch (Exception e) {
System.out.println("Portefeuille: Exception is caught");
Portefeuille p = new Portefeuille();
return p;
}
}
}
EDIT
I fixed it myself. Thanks for answering you all :)
You could define, on the top-level class, a method like getSortableValue(), and implement it to return a default field (you didn't mention the field you need to sort on for Woningen). In the KoopWoning you override this method to return the energyLevel instead. Then you always sort on the value returned by getSortableValue().
You can let the them implement Comparable, so like Woning implements Comparable<Woning>. This will let you implement the (required) method:
#override
public int compareTo(Woning other) {
int result = Integer.compareto(maxPrijs, other.maxPrijs);
if (result != 0) return result;
result = Integer.compareto(someField, other.someField);
if (result != 0) return result;
// etc...
return 0;
}
The subclass KoopWoning extends Woning implements Comparable<KoopWoning> can have a method like this:
#override
public int compareTo(KoopWoning other) {
int result = Integer.compareto(energylevel, other.energylevel);
if (result != 0) return result;
return super.compareTo(other);
}
Then all you need to do is load all the Woning instances in a list and execute
Collections.sort(list);
Having subclasses inherit Comparable is optional, so HuurWoning will just sort like Woning.
You could define a Comparator on Woning that determines the relative ordering of two Woning. You could do this either by having a method that looks at the actual types of the two arguments and then acts appropriately, or, better, by having an overrideable method of Woning that returns some value that you can use for sorting purposes.
If, for instance, you decide that anything with an energy level should come after anything without one, then you can have KoopWoning return something with the energy level in the high order bits of a long, so that it always comes out higher than anything without one (essentially you'd be setting a default energy level of zero).
Then, you can use
Collections.sort(arrayList, myComparator);
to sort the list based on the Comparator you've created.
There are some nice classes in the Guava library that help with Comparator building on multiple keys, but if your case is fairly simple, you probably won't need them.
I have several properties in a Java Bean that does not look pretty. E.g. max_speed. There are too many properties for me to want to manually write them up in my HTML-file so they look pretty.
Current output: max_speed, min_speed
Wanted output: Max Speed, Min Speed
Question: How do I map "max_speed", "min_speed" and 20 other properties to "Max Speed", "Min Speed" etc., for pretty output print? Is this doable without having to write them up manually every time I want to add them to a web page?
Check out these functions below;
To Set the Display Name
public void setDisplayName(String givenProperty){
String displayName = null;
// Perform Some Operation to generate you display Name
// String [] tokens = givenProperty.split("_");
// displayName = tokens[0] + " " + tokens[1];
objectOfHashMap.put(givenProperty,displayName);
}
To get the DisplayName:
public String getDisplayName(HashMap<String, String> givenHashMap, String givenProperty){
String outputString = null;
for(Map.Entry<String, String> pairs1 : givenHashMap.entrySet()){
if(givenProperty.equals((String)pairs1.getKey())){
outputString = pairs1.getValue();
}
}
return outputString;
}
Let me know, if you have any questions.
What if you write a method, that expects a field name (property name) and returns a nicely formatted output?
For example:
public String formatProperty(String propertyName, String userFriendlyLabel) {
Field someField = this.getClass().getField(propertyName);
Object value = null;
if(someField != null) {
value = someField.get(this);
}
return userFriendlyLabel + ": " + value;
}
The code shown below will work for your specific use case:
It return formatted names for all methods and properties defined in a specific class if that class contains the property with "_" in it.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class ReplaceMethodNames {
/**
* #param args
*/
String max_speed;
String min_speed;
public static void main(String[] args) {
// Provide the class Name as parameter you may want to format
List<String> formattedNames =getFormattedProperties(ReplaceMethodNames.class);
System.out.println(formattedNames);
}
public static List<String> getFormattedNames(Class clazz){
List<String> formattedNames = new ArrayList<String>();
Method[] methods = clazz.getMethods();
for(Method method:methods){
String methodName = method.getName();
StringBuilder newMethodName = new StringBuilder();
for(int i = 0 ; i<methodName.length();i++){
if(methodName.charAt(i)=='_') {
newMethodName.append(' ');
newMethodName.append(Character.toUpperCase(methodName.charAt(i+1)));
i++;
}else if(i==0){
newMethodName.append(Character.toUpperCase(methodName.charAt(i)));
}else {
newMethodName.append(methodName.charAt(i));
}
}
if(methodName.contains("_")){
formattedNames.add(newMethodName.toString());
}
}
return formattedNames;
}
public static List<String> getFormattedProperties(Class clazz){
List<String> formattedNames = new ArrayList<String>();
Field[] fields = clazz.getDeclaredFields();
for(Field field:fields){
String methodName = field.getName();
StringBuilder newMethodName = new StringBuilder();
for(int i = 0 ; i<methodName.length();i++){
if(methodName.charAt(i)=='_') {
newMethodName.append(' ');
newMethodName.append(Character.toUpperCase(methodName.charAt(i+1)));
i++;
}else if(i==0){
newMethodName.append(Character.toUpperCase(methodName.charAt(i)));
}else {
newMethodName.append(methodName.charAt(i));
}
}
if(methodName.contains("_")){
formattedNames.add(newMethodName.toString());
}
}
return formattedNames;
}
public static void test_methodA(){}
public static void test_methodB(){}
public static void test_methodC(){}
public static void test_methodD(){}
}
I ended up with this method for prettyfying(if that is allowed as a word) my properties, and adding some if else sentences for the special cases. Couldn't use switch case because Java 1.6 does not support switching on String, apparently. Notice the WordUtils-package from commons. NB: Notice that this only works for my special case, where all property-names are divided by underscores.
public String niceDisplayName(String property) {
String[] tokens = property.split("_");
StringBuilder sb = new StringBuilder();
for (int i=0;i<tokens.length;i++) {
tokens[i] = WordUtils.capitalize(tokens[i]);
sb.append(tokens[i]);
if((i+1) < tokens.length) {
sb.append(" ");
}
}
return sb.toString();
}