This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
What does it mean to return a value?
(3 answers)
Closed 5 years ago.
guys i am a beginner in java ... i want to make a function to loop through a hashmap for example it contains
0[3],3[4,5],6[2]
and to break when the method isSiteInherited is true else return false... here is what i made
private boolean isInherited() {
boolean isInherited = false;
for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
for (Integer index : entry.getValue()) {
if(isSiteInherited(index)){
break;
}
}
}
return false;
}
if not sites are found inherited return false and if it enters the break it should break from all the method ... so what is wrong with this method
Seems to be like you want to return instead of break. Without the use of labels, break only gets you out of one layer of loops anyway, and in this case, you need to report overall success, which isn't something your current approach does.
private boolean isInherited() {
for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
for (Integer index : entry.getValue()) {
if (isSiteInherited(index)) {
return true;
}
}
}
return false;
}
You can either use a label to break from the outer loop (https://stackoverflow.com/a/886979/4949918).
The better way would probably be to use a boolean to say that you've broken from the inner loop in the outer loop.
private boolean isInherited() {
boolean isInherited = false;
boolean shouldBreak = false;
for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
for (Integer index : entry.getValue()) {
if(isSiteInherited(index)){
shouldBreak = true;
break;
}
}
if (shouldBreak) {
break;
}
}
return false;
}
Related
This question already has answers here:
Break or return from Java 8 stream forEach?
(14 answers)
Closed 4 years ago.
I have a for loop for a list that checks whether or not index values exist in the db.
Simply if any value doesn't exist, it immediately returns false.
public boolean exists(List<String> keys) {
for(String key: keys) {
boolean exists = service.existsByKey(key);
if(!exists) return false;
}
return true;
}
I tried to change it to java 8 foreach, but it doesn't work as expected.
keys.stream().forEach(k -> {
boolean exists = service.existsByKey(k);
if(!exists) return false;
});
Am I missing something? Why doesn't it go in if(!exists) staetment in forEach()?
Your return statements in forEach method are ignored.
Try to use
boolean exists = key.stream().allMatch(k -> service.existsByKey(k));
You cannot return a value with the forEach construct as it accepts a consumer i.e. a function that takes one parameter and returns nothing(void), instead, you can use allMatch as shown in the other answer ornoneMatch like this:
return keys.stream()
.noneMatch(key -> !service.existsByKey(key))
You use lambda that is mostly a shortcut for anonymous class.
So your code is equivalent to:
keys.stream().forEach(new Consumer<String>() {
#Override
public void accept(String s) {
boolean exists = service.existsByKey(k);
if(!exists) return false;
}
});
It doesn't return from your method (actually it doesn't compile also).
This question already has answers here:
Remove specific index from array in java
(6 answers)
Why we need to override hashCode and equals?
(4 answers)
Closed 5 years ago.
I have created an array of objects (object representing a flight),
and i'm trying to create a method to remove a specific object from that array, without changing it's length.
I have written the following method :
public boolean removeFlight (Flight f) {
for (int i = 0 ; i < _noOfFlights ; i++) {
if (_flightsSchedule[i].equals(f)) {
_flightsSchedule[i] = _flightsSchedule[(i+1)];
_noOfFlights--;
return true;
}
}
return false;
}
_noOfFlights represents the number of object currently in the array.
For some reason it returns "false" when given an object that was added to the array.
You need to be careful not to change the ground under your feet. You also don't want to return in the middle of the loop, otherwise you won't have moved all the elements properly.
You could do something like this:
public boolean removeFlight (Flight f) {
boolean found = false;
for (int i = 0 ; i < _flightsSchedule.length; i++) {
if (f.equals(_flightsSchedule[i])) {
found = true;
} else if (found) {
_flightsSchedule[i - 1] = _flightsSchedule[i];
}
}
if (found) {
_noOfFlights--;
_flightsSchedule[_flightsSchedule.length - 1] = null;
}
return found;
}
Also, note that I've set the last element to null to avoid an inadvertent memory leak.
This question already has answers here:
Java - adding elements to list while iterating over it
(5 answers)
Closed 5 years ago.
am trying to add objects to an arraylist after verifying either that object already exits in the list or not. But am getting a ConcurrentModificationException and I don't know how to fix it.
Any help?
here is the code that throws the exception:
List<ContexteNb> projets = service.findByprojet(p);
List<ProjetVTO> models = new ArrayList<>();
for (ContexteNb contexteNb : projets) {
ProjetVTO model = new ProjetVTO();
model.setNbillets(contexteNb.getNbBillet());
model.setAnnee(contexteNb.getDimDate().getAnnee());
model.setPriorite(contexteNb.getDimPriorite().getPriorite());
if (models.isEmpty()) {
models.add(model);
}
else{
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee())
&& (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
} else {
models.add(model);
}}}}
thanks,
The exception results from adding an element to the models List while iterating over it.
You have to change your logic. I suspect the logic of your inner loop is wrong anyway, and fixing it will also solve your problem. You probably want to search first if the List contains any element matching model and modify it if found, and only add a new instance to the List if you don't find a match (i.e. after the loop is over).
Your inner loop would look like this:
if (models.isEmpty()) {
models.add(model);
} else {
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}
}
or simply (you can eliminate the outer condition):
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public static boolean stringToBoolean (String horv) {
if (horv == "H") {
return true;
} if (horv == "V") {
return false;
} else {
return true;
}
This is a small part of a program I am creating. The program is reading from a file and inputting the data into an array. For this part it is reading what will either be a "H" or "V" from the file and converting it to a boolean value. The problem is when I run the program I am only getting true for every value, even the ones that have a "V" as their variable.
Change the code to be:
if ("H".equals(horv)) { return true; }
...
Try This
public static boolean stringToBoolean (String horv) {
if ("H".equals(horv)) { // use equals method for string comparison
return true;
} if ("V".equals(horv)) {
return false;
} else {
return true;
}
String variables should be compared with equals() method in java.
In Java you have compare String with a method equals() Like this
public static boolean stringToBoolean (String horv) {
if (horv.equals("H")) return true;
if (horv.equals("V")) return false;
return true;
}
I have a problem with this method:
private boolean reflectionEqualsSet(Object left, Object right) {
Set leftSet = (Set) left;
Set rightSet = (Set) right;
if (leftSet == null) {
// POF tricks: if set to serialize is null, the deserialized set is empty
return rightSet != null && rightSet.size() == 0;
}
// check size
if (leftSet.size() != leftSet.size()) {
return false;
}
// check values
for (Object currLeft : leftSet) {
boolean found = false;
for (Object currRight : rightSet) {
if (isEqual(currLeft, currRight)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
The problem is:
I have an object with three random filled values in leftSet (2 UUID's and 1 Integer).
The values I have in my leftSet change completely in the for loop. While debugging I've found out that in the first iteration currSet already has completely different values and I can't figure out why.
In the inner loop with currRight this doesn't happen.
I've been debugging for hours and I've found the problem is in that line does anyone have an idea of why the values change? (Not the order, the values).
I know this isn't much information about the problem but that's all I can tell, I don't know how to explain it any better, sorry.
Thanks
First, your size check is off
// check size
// if (leftSet.size() != leftSet.size()) {
if (leftSet.size() != rightSet.size()) {
return false;
}
Next, I don't trust your isEqual method - please Override Object.equals(Object),
// if (isEqual(currLeft, currRight)) {
if (currLeft.equals(currRight)) {
return true; // <-- and just short-circuit with return true!
}
Obviously return false; after your for loop, and you can eliminate found.