Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Example:
Input: abc565xyz
Output: 16
Which variant would be better? Thanks.
public static int sumOfDigits(String s) {
return s.chars().filter(Character::isDigit).reduce(0, (i0, i1) -> i0 + Character.digit(i1, 10));
}
public static int sumOfDigits(String s) {
return s.chars().filter(Character::isDigit).mapToObj(a -> a - '0').reduce(0, (a, b) -> a + b);
}
public static int sumOfDigits(String s) {
return s.chars().filter(Character::isDigit).mapToObj(a -> Character.digit(a, 10)).reduce(0, Integer::sum);
}
Define better. What version of Java? Which release? Which platform are you planning on running it? In short, without testing it on the target platform it's very hard to say.
BTW, instead of mapToObj and an explicit reduce, it would be better to do
return s.chars().filter(Character::isDigit).map(a -> Character.digit(a, 10)).sum();
Mapping an int to an Object is probably the most expensive part and you did that in two of your versions. So, as posted, the first one is probably "best".
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm not sure if I'm overthinking this but should I do this
if (!searchList.isEmpty()) {
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
} else {
return null;
}
or should I do this
if (!searchList.isEmpty()) {
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
}
return null;
Some advice :
You should never return a null value. It is a bad practice
You should test for true instead of false. It makes your code more readeable
Your should look like this :
if (searchList.isEmpty()) {
return Collections.emptyList();
}
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
Neither.
if (searchList.isEmpty()) {
return null;
}
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
I didn't like the negative condition ("if not empty") when it wasn't really needed.
The way I think of what I wrote, it's "get rid of the edge case first, then deal with the main logic".
This is of course mere opinion. Eventually you'll develop your own taste for how to lay out code; and good taste is one of the more important attributes of a programmer.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a method:
public void dealDmg(int hp) {
this.hp = hp;
this.hp -= this.dmg;
}
But when i use it as dmg_dealer.dealDmg(dmg_receiver.hp);, it doesn't work properly as in the dmg_receiver's hp is not decreased, but the dmg_dealer's hp becomes of the same amount as of the dmg_receiver, and then dmg_dealer's hp gets reduced by the dmg amount. How can I change a body of the method so that it works in such a way?
You need to pass in the dmg_receiver object to the method instead of dmg_receiver.hp, that way you can update hp in dmg_receiver as well. The updated method should look like below:
public void dealDmg(DmgReceiver dmg_receiver) {
this.hp = dmg_receiver.hp;
dmg_receiver.hp -= this.dmg;
}
If the object represented by this is dealing damage to another object, the dealDmg needs to the object being dealt damage to (assuming that dmg is a member):
public void dealDmg(Unit other) {
other.hp -= this.dmg;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have this code:
entity.conditions().forEach(entityCondition - > {
if (entityCondition instanceof LinkCondition) {
LinkCondition condition = (LinkCondition) entityCondition;
} else if (entityCondition instanceof OppositeLinkCondition) {
//...
} else if (entityCondition instanceof PropertyEqualCondition) {
//...
} else if (entityCondition instanceof PropertyLocalTimeRangeCondition) {
//...
}
// and 20 or so, more conditions...
});
In which I am looking for an alternative than IF-ELSE statement, a more elegant approach in dealing with dozens of instanceof conditions.
Unfortunately, there is no such syntax in Java yet. You can try Kotlin which already supports this:
val b = when (a) {
is String -> a.length
is Int -> a
is Long -> (a and 0xFFFFFFFF).toInt()
else -> a.hashCode()
}
As #Progman pointed out, this question is similar to other questions, you should check them out too.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
So in an attempt to keep up with the times, I would like to learn what I can about Java 8's new functional operations. Beyond the opinions of which looks nicer, which is totally opinion based, would someone like to describe in detail the positives(and possibly negatives) in using Java 8's new functional programming style to iterate arrays?
This is what I mean:
Pre-Java 8:
for(Object item: itemList){
item.doSomething();
}
Java 8:
itemList.stream().forEach((item) -> {
item.doSomething();
});
The answers have enlightened me, so I will write something to demonstrate it's potential.
static int pos = 0;
public static void main(String[] args) {
List<Worker> workers = Arrays.asList(new Worker[1000]);
workers.replaceAll(worker -> new Worker(pos++));
workers.parallelStream().forEach(Worker::startJob);
}
public static class Worker {
final int pos;
public Worker(int pos) {
this.pos = pos;
}
public synchronized void startJob() {
try {
wait(100);
} catch (InterruptedException ex) {
Logger.global.log(Level.SEVERE, null, ex);
}
System.out.println("Finished... " + pos);
}
}
Only a partial answer, but the general point of the iterators is moving from external iteration to internal iteration. The foreach just a replacement, but consider something like the following (from Java 8 Lambdas) simulating the throwing of two dice:
public Map < Integer, Double > parallelDiceRolls() {
double fraction = 1.0 / N;
return IntStream.range( 0, N) .parallel()
.mapToObj( twoDiceThrows())
.collect( groupingBy( side -> side, summingDouble( n -> fraction)));
}
This is running a parallel operation against the stream, removing all external iteration requirements and all manual threading requirements. It replaces 50-60 lines of code.
It also moves from a focus on how to accomplish something (such as the OP's pre-Java 8 example) to what to accomplish.
Consider a Artist class that has an .isFrom(String) method. In the OP's first example, to count how many are from Liverpool, the code would be something like:
int count = 0;
for (Artist artist : allArtists) {
if (artist.isFrom("Liverpool")) {
count++;
}
}
Notice that the the desire to accumulate is lost in the loop and the filtering. Contrast with:
allArtists.stream()
.filter(artist -> artist.isFrom("Liverpool")
.count();
Now the logic is clear -- a filtering and a count. The iteration is now internal rather than external.
There are many additional examples, rationales, and preferences. But I think it is more than "beauty" -- it is a focus on the what, not the how when one considers iteratation.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a code (Java for example):
boolean A(...){
if (...) return true;
else return false;
}
void C(...){
if (A) {doSomeThing();}
else {doNothing();}
}
But logic is changed and today i need return 3 cases. It look something like this
int A(...){
if (...){ return int;}
else {
if (...) {return int;}
else {return int;}
}
}
void C(...){
if (A == 1) {doSomeThing1();}
if (A == 2) {doSomeThing2();}
if (A == 3) {doSomeThing3();}
}
Is this a best practices or I should use something other instead of "int"? Or I should change my logic and divide it on two boolean?
P.S. I know that this questions are fully but it disturbs me.
Best practice would be to use enum type instead of boolean.
public enum PossibleValues {
TRUE, FALSE, NEITHER;
}
Actually how many condition you should check is depends on your requirement. For that you can use if-else or swith-cases.