Compute percentage for bigdecimals - java

I haven't found any native method to do this, so I created my own in a helper class:
public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
return base.multiply(pct).divide(new BigDecimal(100));
}
But I don't quite like it, I wonder if the API has something similar. The Number class (ancestor of BigDecimal) would be a nice place.

I don't think there is an API for that (I never needed it).
Your solution seams good to me, maybe you just add the constant ONE_HUNDRED:
public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
return base.multiply(pct).divide(ONE_HUNDRED);
}
probably not that much gain, only if called very often
eventually put it in some Util class...

You may want to implement the division by 100 using BigDecimal.scaleByPowerOfTen(-2).
It adds up if you do it a million times. It is much faster in my experience.
There is also a similar method BigDecimal.movePointLeft(2) - see the other thread for details and decide which one works better for you.

Feel free to subclass BigDecimal and add that method. Beyond that, what do you expect? You know where to find the API and confirm that the class you would like to have that method doesn't. Personally, I'd say the functionality is so trivial that there wouldn't be much of a point in having it in the standard API.

See also DecimalFormat. You can use the parent's factory method NumberFormat.getPercentInstance() as shown here, here, et al.

Related

Efficient comparison between two POJOs to determine the extent of how similar they are

I need to make a comparison between 2 POJOs, but instead of checking for equality, I'm trying to determine how similar they are even though I know they are not the same. For instance, out of the 20 fields they have, I need to determine how many are the same/different.
ex:
public class Objekt {
private int field1;
private String field2;
private String field3;
...
private List<Integer> field4;
public Objekt () {
...
}
public compareWith (Objekt other) {
if (field1 != other.field2)
System.out.println("Field 1 is different");
if (!field2.equals(other.field2))
System.out.println("Field 2 is different");
...
// etc
}
}
Having to compare each field manually seems like a lot of extra boilerplate code, and it's also not scalable if I were to need a method similar to this with other object. I was curious if there's a solution out there to do something similar, or if anyone has any ideas on how I could make this more efficient?
New to StackOverflow, thanks for any suggestions! :)
The simple answer is: Java isn't built for "unstructured" code like you have in mind.
Meaning: there is reflection (see https://www.oracle.com/technetwork/articles/java/javareflection-1536171.html) for example that allows you to write code that inspects the fields of objects arbitrary classes. But that is extremely cumbersome and error prone, and of course: coming at high performance penalties at runtime.
There are libraries build around that though, like the https://commons.apache.org/proper/commons-lang/javadocs/api-3.5/org/apache/commons/lang3/builder/EqualsBuilder.html that make things a bit easier to use.
But as said: the real answer is that you normally strive to avoid such designs. You should rather step back and find ways to solve the underlying problem that have better solutions in Java. Or ask yourself why you want to use a statically typed language like Java for a problem that dynamic languages are much better suited for.

What is the of method in java?

What is
import static java.util.stream.IntStream.of;
I saw it is used to find the sum of some numbers like this,
(array of numbers).sum()
what does it do ?
What is the of method in java?
There is no of method in Java. But there is an IntStream.of method, and so on. In fact there are roughly 100 distinct of methods in the Java 8 APIs.
What is import static java.util.stream.IntStream.of; ?
It is a static import.
what does it do?
The purpose is to allow this class to refer to the static method IntStream.of as of ... with no qualification.
Without it, you would need to write:
of(<array of numbers>).sum()
as
IntStream.of(<array of numbers>).sum()
However, the latter would be the better way to write this. (IMO) Especially considering how many different of methods there are.
#Louis Wasserman comments:
What it does is make your code harder to read. Some methods just shouldn't be static imported.
I agree with that. Some people are obsessed with conciseness at the expense of maintainability. This is not an example that is good to copy.
Creates a new IntStream object with the integers you specify: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#of-int-
For future questions make sure you refer to the Java documentation, most of the information you need is there.
This is equal to IntStream.of(array of numbers).sum(), which pipes the array of numbers into an IntStream and calls sum on the stream to evaluate the sum of its values by reduction.

Is it inefficient to reference a hashmap in another class multiple times?

Class A
Class A {
public HashMap <Integer,Double> myHashMap;
public A(){
myHashMap = new HashMap()
}
}
class B
Class B {
private A anInstanceOfA;
public B(A a) {
this.anInstanceOfA = a;
}
aMethod(){
anInstanceOfA.myHashMap.get(1); <--getting hashmap value for key = 1
//proceed to use this value, but instead of storing it to a variable
// I use anInstanceOfA.myHashMap.get(1) each time I need that value.
}
In aMethod() I use anInstanceOfA.myHashMap.get(1) to get the value for key = 1. I do that multiple times in aMethod() and I'm wondering if there is any difference in efficiency between using anInstanceOfA.myHashMap.get(1) multiple times or just assigning it to a variable and using the assigned variable multiple times.
I.E
aMethod(){
theValue = anInstanceOfA.myHashMap.get(1);
//proceed to use theValue in my calculations. Is there a difference in efficiency?
}
In theory the JVM can optimise away the difference to be very small (compared to what the rest of the program is doing). However I prefer to make it a local variable as I believe it makes the code clearer (as I can give it a meaningful name)
I suggest you do what you believe is simpler and clearer, unless you have measured a performance difference.
The question seems to be that you want to know if it is more expensive to call get(l) multiple times instead of just once.
The answer to this is yes. The question is if it is enough to matter. The definitive answer is to ask the JVM by profiling. You can, however, guess by looking at the get method in your chosen implementation and consider if you want to do all that work every time.
Note, that there is another reason that you might want to put the value in a variable, namely that you can give it a telling name, making your program easier to maintain in the future.
This seems like a micro-optimization, that really doesn't make much difference in the scheme of things.
As #peter already suggested, 'optimizing' for style/readability is a better rationale for choosing the second option over the first one. Optimizing for speed only starts making sense if you really do a lot of calls, or if the call is very expensive -- both are probably not the case in your current example.
Put it in a local variable, for multiple reasons:
It will be much faster. Reading a local variable is definitely cheaper than a HashMap lookup, probably by a factor of 10-100x.
You can give the local variable a good, meaningful name
Your code will probably be shorter / simpler overall, particularly if you use the local variable many times.
You may get bugs during future maintenance if someone modifies one of the get calls but forgets to change the others. This is a problem whenever you are duplicating code. Using a local variable minimises this risk.
In concurrent situations, the value could theoretically change if the HashMap is modified by some other code. You normally want to get the value once and work with the same value. Although if you are running into problems of this nature you should probably be looking at other solutions first (locking, concurrent collections etc.)

Standard API way to check if one array is contained in another

I have two byte[] arrays in a method like this:
private static boolean containsBytes(byte[] body, byte[] checker){
//Code you do not want to ever see here.
}
I want to, using the standard API as much as possible, determine if the series contained in the checker array exists anywhere in the body array.
Right now I'm looking at some nasty code that did a hand-crafted algorithm. The performance of the algorithm is OK, which is about all you can say for it. I'm wondering if there is a more standard api way to accomplish it. Otherwise, I know how to write a readable hand-crafted one.
To get a sense of scale here, the checker array would not be larger than 48 (probably less) and the body might be a few kb large at most.
Not in the standard library (like Jon Skeet said, probably nothing there that does this) but Guava could help you here with its method Bytes.indexOf(byte[] array, byte[] target).
boolean contained = Bytes.indexOf(body, checker) != -1;
Plus, the same method exists in the classes for the other primitive types as well.
I don't know of anything in the standard API to help you here. There may be something in a third party library, although it would potentially need to be implemented repeatedly, once for each primitive type :(
EDIT: I was going to look for Boyer-Moore, but this answer was added on my phone, and I ran out of time :)
Depending on the data and your requirements, you may find that a brute force approach is absolutely fine - and a lot simpler to implement than any of the fancier algorithms available. The simple brute force approach is generally my first port of call - it often turns out to be perfectly adequate :)
You probably already know this, but what you're trying to (re-)implement is basically a string search:
http://en.wikipedia.org/wiki/String_searching_algorithm
The old code might in fact be an implementation of one of the string search algorithms; for better performance, it might be good to implement one of the other algorithms. You didn't mention how often this method is going to be called, which would help to decide whether it's worth doing that.
The collections framework can both cheaply wrap an array in the List interface and search for a sublist. I think this would work reasonably well:
import java.util.Arrays;
import java.util.Collections;
boolean found = Collections.indexOfSubList(Arrays.asList(body), Arrays.asList(checker) >= 0;

public (static) swap() method vs. redundant (non-static) private ones

I'm revisiting data structures and algorithms to refresh my knowledge and from time to time I stumble across this problem:
Often, several data structures do need to swap some elements on the underlying array. So I implement the swap() method in ADT1, ADT2 as a private non-static method. The good thing is, being a private method I don't need to check on the parameters, the bad thing is redundancy. But if I put the swap() method in a helper class as a public static method, I need to check the indices every time for validity, making the swap call very unefficient when many swaps are done.
So what should I do? Neglect the performance degragation, or write small but redundant code?
Better design should always trump small inefficiencies. Only address performance problem if it actually is proven to be one.
Besides, what kind of checking are you doing anyway? Aren't naturally thrown ArrayIndexOutOfBoundsException and/or NullPointerException good enough?
It's worth nothing that while there's public static Collections.swap(List<?>,int,int), java.util.Arrays makes its overloads (for int[], long[], byte[], etc) all private static.
I'm not sure if Josh Bloch ever explicitly addressed why he did that, but one might guess that it has something to do with Item 25 on his book Effective Java 2nd Edition: Prefer lists to arrays. Yes, there will be "performance degradation" in using List, but it's negligible, and the many advantages more than make up for it.
If you don't need to make the checks in the private method, don't make them in the static one. This will result in a RuntimeException for invalid calls, but since all your calls are supposed to be valid, it will be as though you've used a private method.
It's always better for your code to be less efficient than to be duplicated (some constant calls are not considerable). At least that is what is taught at my university.
Code duplication produces bugs. So you prefer your program to work correctly rather than to work a little faster.
If you want to prevent constraints checking: what comes to my mind is that you can either accept naturally thrown exceptions as polygenelubricants suggested or create an abstract super class to all your data structures based on arrays. That abstract class would have protected method swap that will not check parameters. It's not perfect, but I guess that a protected method that does not check parameters is better than a public method that does not do it.

Categories

Resources