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();
}
Related
The input is String array as below,
{"1112323 400 error","1112323 400 error","9988778 400 error"}
I need to print the timestamp i.e the number at the start of the sentences and its frequency throughout the array
I've come only this far as of now. Only have been able to find the string if it is known already.
int count = 0;
for(int i=str1.length-1;i>=0;i--)
{
String[] ElementOfArray = str1[i].split(" ");
for(int j=0;j<ElementOfArray.length-1;j++)
{
if(ElementOfArray[j].equals("Hi"))
{
count++;
}
}
}
System.out.println(count);
One approach is to keep track of the number of entries, and increment.
public static void main(String[] args)
{
String[] inp = {"1112323 400 error",
"1112323 400 error",
"9988778 400 error"};
Map<String,Integer> results = new HashMap<>();
for (String one : inp) {
String[] parts = one.split(" ");
String ts = parts[0];
int val = results.computeIfAbsent(ts, v-> 0);
results.put(ts, ++val);
}
System.out.println(results);
}
Note: there are other ways to handle the map incrementing. This is just one example.
Sample Output:
{1112323=2, 9988778=1}
Now, if in the future one might want to perform other operations, using objects might be of interest.
So a class might be:
private static class Entry
{
private final String ts;
private final String code;
private final String desc;
public Entry(String ts, String code, String desc)
{
// NOTE: error handling is needed
this.ts = ts;
this.code = code;
this.desc = desc;
}
public String getTs()
{
return ts;
}
public static Entry fromLine(String line)
{
Objects.requireNonNull(line, "Null line input");
// NOTE: other checks would be good
String[] parts = line.split(" ");
// NOTE: should verify the basic parts
return new Entry(parts[0], parts[1], parts[2]);
}
// other getter methods
}
And then one could do something like:
List<Entry> entries = new ArrayList<>();
for (String one : inp) {
entries.add(Entry.fromLine(one));
}
Map<String,Integer> res2 = entries.stream()
.collect(Collectors.groupingBy(x->x.getTs(),
Collectors.summingInt(x -> 1)));
System.out.println(res2);
(same sample output at the moment). But if one needs to extend to count the number of 400 codes or whatever, it is trivial to change the stream since the object has the data. Of course, there are even more extensions to this approach.
You can use HashMap to solve count the frequency of timestamps.
import java.util.HashMap;
public class test {
public static void main(String[] args) {
// Create a HashMap object called timeFrequency
HashMap<String, Integer> timeFrequency = new HashMap<String, Integer>();
String []str1 = {"1112323 400 error","1112323 400 error","9988778 400 error"};
for(int i=0;i<str1.length;i++)
{
String[] ElementOfArray = str1[i].split(" ");
if(timeFrequency.containsKey(ElementOfArray[0])){
timeFrequency.put(ElementOfArray[0], timeFrequency.get(ElementOfArray[0]) + 1);
}else{
timeFrequency.put(ElementOfArray[0], 1);
}
}
System.out.println(timeFrequency);
}
}
Output:
{1112323=2, 9988778=1}
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
I have a hashmap containing Key and Value <String, String>.
i.e. mapValue:
mapValue.put("A","B-7");
mapValue.put("B","START+18");
mapValue.put("C","A+25");
Now I want to evaluate expression for 'C'. So for C, the expression would be
replaced by (((START+18)-7)+25).
So if anymethod, I will pass the string C, it should return string
"(((START+18)-7)+25)" and also I want to evaluate it as per the priority.
Thanks
generally logic of such function (assuming, you know possible operations and syntax is strict) may as follows:
public String eval(HashMap<String, String> mapValue, String variable) {
//get expression to be evaluated
String tmp = mapValue.get(variable);
// For each knwon operation
for (String op : OPERATIONS) {
// split expression in operators in Array
String[] vars = tmp.split("\\" + op);
// for each Element of splitted expr. Array
for (int i = 0; i < vars.length; i++) {
//Check if Element is a valid key in HashMap
if (mapValue.containsKey(vars[i])) {
//if it is replace element with result of iteration
vars[i] = eval(mapValue, vars[i]); // DO ITERATION
}
//if Element is not a valid key in has do nothing
}
//Join splitted string with proper operator
tmp = join(vars, op);
}
//return in parenthesis
return "(" + tmp + ")";
}
The result of 'eval(mapValue,"C")' would be:
(((START+18)-7)+25)
Some short join function may be implemented as follows:
public String join(String[] arr, String d) {
String result = arr[0];
int i = 1;
while (i < arr.length) {
result += d + arr[i];
i++;
}
return result;
}
All code provided above is more to illustrate logic, as some exception handling, better operations with string etc should be used.
Hope it helps
Cheers!
As mentioned in the comments I would not recommend recursion - it can lead to stackoverflow-Exceptions, if the recursion gets too deep.
Also I would recommend not to use String equations. Strings are slow to parse and can lead to unexpected results (as mentioned by #rtruszk "START" contains variable "A").
I created an example as my recommendation:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class X {
static interface Expression {
}
static class Combination implements Expression {
Expression[] values;
public Combination(Expression... values) {
this.values = values;
}
#Override
public String toString() {
return "?";
}
}
static class Reference implements Expression {
private String reference;
public Reference(String reference) {
this.reference = reference;
}
#Override
public String toString() {
return reference;
}
}
static class Number implements Expression {
private int value;
public Number(int value) {
this.value = value;
}
#Override
public String toString() {
return ""+value;
}
}
public static void main(String[] args) {
Map<String, Expression> mapValue = new HashMap<>();
mapValue.put("START", new Number(42));
String x = "C";
mapValue.put("A", new Combination( new Reference("B"), new Number(-7)));
mapValue.put("B", new Combination(new Reference("START"), new Number(+18)));
mapValue.put("C", new Combination( new Reference("A"), new Number(+25)));
int result = 0;
ArrayList<Expression> parts = new ArrayList<>();
parts.add(mapValue.get(x));
while (!parts.isEmpty()) {
debuggingOutput(x, result, parts);
Expression expression = parts.remove(0);
if (expression instanceof Combination)
parts.addAll(Arrays.asList(((Combination) expression).values));
else if (expression instanceof Reference)
parts.add(mapValue.get(((Reference) expression).reference));
else if (expression instanceof Number)
result += ((Number) expression).value;
}
System.out.println(result);
}
private static void debuggingOutput(String x, int result, ArrayList<Expression> parts) {
System.out.print(x);
System.out.print(" = ");
System.out.print(result);
for (Expression part : parts) {
System.out.print(" + ");
System.out.print(part);
}
System.out.println();
}
}
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.