Using Comparator in an object [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a class named Age which has the attributes Years, months and days.
I also have a list of Age instances. I would like to find the maximum age from that list. To do so I would like to use the Comparator class.
Any help would appreciated.

If U would like to make for each field his own Comparator do like this
public static Comparator<Age> yearComparator = new Comparator<Age>() {
#Override
public int compare(Age age1, Age age2) {
return age1.getYear() - age2.getYear();
}
};
And then
Arrays.sort(yourAgesArray, Age.yearComparator);
Or
Collections.sort(yourAgesArray, Age.yearComparator);
Read this article to understand this better.

You can write a comparator which would look something like this:
Comparator<Age> ageComparator = new Comparator<Age>() {
#Override
public int compare(Age age1, Age age2) {
if(age1.getYear() != age2.getYear()) {
return age1.getYear() < age2.getYear() ? -1 : 1;
} else if(age1.getMonth() != age2.getMonth()) {
return age1.getMonth() < age2.getMonth() ? -1 : 1;
} else if(age1.getDay() != age2.getDay()) {
return age1.getDay() < age2.getDay() ? -1 : 1;
} else {
return 0;
}
}
}

You should probably implement the Comparable interface in your Age class. However, you should maybe consider using a 3rd party time handling library or use the one from java.time (depending on which version of Java are you using). Comparing time can sometimes get messy.
When your class implements the Comparable interface you can use the Arrays.sort() method from the platform.

From Java 8, you can use this one-line solution :
Age maxAge = collection
.stream()
.max(
Comparator.comparing(Age::getYear)
.thenComparing(Age::getMonth)
.thenComparing(Age::getDay)
)
.get();

Related

Is something wrong with the method? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
So that's my method and i got Main class from my teacher that uses this method and it should return only 1 Suspect but it returns the same one for 8 times or something i am really close on my deadline please help
public ArrayList<Suspect> getCommonPartners(Suspect aSuspect) {
ArrayList<Suspect> commonpartners = new ArrayList<>() ;
for(Suspect s: partners) {
for(Suspect sus: aSuspect.getPartners()) {
if(s.getCodename().equals(sus.getCodename())) {
commonpartners.add(s);
}
}
}
return (commonpartners);
}
Where is 'partners' coming from? You're running a for loop on it. Did you mean aSuspect?
If you are getting multiple of the same value. Do a check on the arraylist before adding it.
public ArrayList<Suspect> getCommonPartners(Suspect aSuspect) {
ArrayList<Suspect> commonpartners = new ArrayList<>() ;
for(Suspect s: partners) {
for(Suspect sus: aSuspect.getPartners()) {
if(s.getCodename().equals(sus.getCodename())) {
if(!commonpartners.contains(s)) {
commonpartners.add(s);
}
}
}
}
return (commonpartners);
}

Lambda functions with Optional instead of nested if else [closed]

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
Optional<String> myData;
Set<String> mySet;
if(myData.isPresent()) {
if(myData.get().contains(“testValue”)) {
mySet.add(“somedata”);
}
}
if(!myData.isPresent()) {
mySet.add(“someotherdata”);
}
I have a scenario like this. Where I have nested if-else block and I need to convert that into Java8 map using lambda functions. How can I do that?
This will reproduce your earlier results but has been slightly altered. I believe that a stream solution is not necessary nor desirable. The following will:
result in an empty set if data is present but not testValue
result in the set containing someotherdata if the data is not present
result in the set containing somedata if the data is present and matches testValue
String result = myData.isPresent() ?
(myData.get().contains("testValue") ? "somedata" : "") :
"someotherdata";
if (!result.isBlank()) {
mySet.add(result);
}
You could rework your Optional use (this only apply to your code, as originally presented [in case you edit it]):
Optional<String> myData = ...;
myData.ifPresent(value -> {
if (value.contains("testValue")) {
mySet.add("somedata"),
}
});
if (!myData.isPresent()) {
mySet.add("someotherdata");
}
If you are using Java 11, you should use:
myData.ifPresentOrElse(
value -> {
if (value.contains("testValue")) {
mySet.add("somedata");
}
},
() -> mySet.add("someotherdata")
);
It is up to you to decide which is better (the first avoid doing mySet.add twice in two part).
[edit] fixed the answer and compilation issues per comment remark.
You can use filter to avoid the nested logic in the present case. Your second case has no nested logic, seems fine as is.
myData.filter(d -> d.contains("testValue"))
.ifPresent(mySet::add);
if(!myData.isPresent()) {
mySet.add(“someotherdata”);
}
Well, if you insist:
Optional<String> myData = Optional.of("x");
Set<String> mySet = myData
.<Set<String>>map(s -> s.contains("testValue") ? Set.of("somedata") : Set.of())
.orElse(Set.of("someotherdata"));
System.out.println(mySet);
Output in this case:
[]
Testing other optionals:
Optional<String> myData = Optional.of("x testValue x");
[somedata]
Optional<String> myData = Optional.empty();
[someotherdata]
My own preference is for the use of ifPresentOrElse() shown in the last half of the answer by NoDataFound.

Cannot remove element from an Array List [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Some background: I am new to Java and am taking a basic java class. I am currently on the final project for the class and completed everything except for this last bit of code. For some reason, I am having the toughest time deleting an element from an array list. Here is the code I am working on:
public static void delete(String bookID) {
for (book eachElement : catalog) {
if (eachElement.getBookID().equals(bookID)) {
catalog.remove(eachElement);
return;
}
}
}
code executes, no run time errors but it won't delete anything.
also, I know everything works prior to the remove statement because I have another method that computes calculations using the same exact for and if statement with a select bookID string.
You should not and cannot remove an Element from a Collection while being in a forEach loop.
Please read the Documentation for ArrayList in Java.
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
There you actually can see, that ArrayList.remove(Object o), removes o if it is in the list, so your method is not needed.
So the answer is, find the book Object with your ID and then remove it. Or better use a Map to store your data.
In your case it would be
Book b = null;
for(Book book : books) {
if(book.getBookId().equals(bookId)) {
b = book.getBookId();
break;
}
}
books.remove(b);
Or if you are into Java8 which you really should be :D
books.stream().filter(b -> b.getBookId().equals(bookId)).getFirst().ifPresent(books::remove);
You need to use iterator, otherwise you will get java.util.ConcurrentModificationException
public static void delete(String bookID) {
for (Iterator<Book> it = catalog.listIterator(); it.hasNext(); ) {
Book book = it.next();
if (book.getBookID().equalsIgnoreCase(bookID)) {
it.remove(book);
return;
}
}
}
Note: equalsIgnoreCase is used to discard case differences.
java.util.ConcurrentModificationException is thrown, because you are doing 2 operations on the list: iteration and removal. So, actually, there is another approach - copy the list on each step of iteration.
public static void delete(String bookID) {
for (Book book : new ArrayList<>(catalog)) {
if (book.getBookID().equalsIgnoreCase(bookID)) {
catalog.remove(book);
return;
}
}
}
Note: Because of performance considerations (quadratic memory usage and linear removal on each step), I don't recommend the last approach. I give this example only to stress out the underlying reason why java.util.ConcurrentModificationException is thrown.
Removal of elements, while an iterator is being used, is undefined.The better approach would be to use removeIf.
catalog.removeIf(eachElement -> eachElement.getBookID().equals(bookId));
You need to use iterator in order to delete item while using loop .
also double check if the id exist (make some System.out.println("test") and check if it is entering the scope).

Having issues with List in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have this class:
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
}
And when I do:
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
It gives Exception in thread "main" java.lang.NullPointerException
Weirdly tho, it only gives an error on "angle.isEmpty()" not on "text.isEmpty()"
Why does it say it is null when I initialize it with:
List angle = new ArrayList();
Edit1:
Full error:
Exception in thread "main" java.lang.NullPointerException
at projectmerger1.Attributes.getHowManyNodes(Attributes.java:55)
at projectmerger1.Project.listGameVariables(Project.java:235)
at projectmerger1.ProjectMerger1.main(ProjectMerger1.java:289)
Java Result: 1
Minor edit:
Line 55 in Attributes Class is
howMany += angle.isEmpty() ? 0 : angle.size();
Edit2:
public class Project {
Game game;
public void listGameVariables() {
System.out.print(game.attributes.getHowManyNodes());
}
}
public class Game {
Attributes attributes = new Attributes();
}
This is my whole setup.
Based on your comments (and your code) one (or both) of your List(s) must be null. I would add a null check like this
howMany += text == null ? 0 : text.size();
howMany += angle == null ? 0 : angle.size();
It's possible you have another method that is "nulling" those fields.
I've compiled and run this code, it prints out 0 with no NullPointerException. There is no way to get this error with the code you provided.
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
public static void main(String[] args) {
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
}
}
The only possible way that this could be happening is if:
angle is being accessed somewhere else and set to null before you call getHowManyNodes().
angle is being "shadowed" by another variable of the same name that you are not showing in your code example.
Ways to debug this:
Make your variables private and final, and see what code they break so you can see if they're being set to null elsewhere.
Put System.out.println(angle) in a block of code under your instantiation of angle, and also in your constructor.
Ways to avoid this bug in the future:
Encapsulate your variables.
Make your methods null-safe.
Set a BreakPoint in the first source code line of your getHowManyNodes() method, start your program in debug mode and try to figure out where the error comes from by using the short cut keys (Eclipse) F5 -> StepInto and F6 -> StepOver. Your source provided looks fine and shouldn't cause any problems. By debugging your application via Eclipse or any other IDE, you should easily find such errors.

set methods in Java

Could anubody explain how to use set methods? Problem:
class Sonum {
private int prior;
public Sonum(int prior) {
this.prior = prior;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
class Tel {
// Please explain how can I set the value for prior? (for example 2)
}
Well, first you need an instance of Sonum on which you want to set the prior value. For example:
class Test {
public void foo() {
Sonum sonum = new Sonum(5);
// Use it with a prior of 5
// ...
sonum.setPrior(10);
// Now use it with a prior of 10
}
}
Sonum mySonum = new Sonum(1); //prior is currently 1
mySonum.setPrior(2); //now prior is 2
Take a deep breath. The Java Tutorial. Read it. You will understand.
Refer
Creating Objects & Using Objects
http://download.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
"Setter methods" aren't magic. They're just regular methods. You need an instance of that class, and then you can call the methods on it. Just like any other Java object.
set method deal with a private value that we would like to prevent the direct way to him using our client, therefor there are get \ set method.
The biggest advantage of get \ set methods is the control ability !
We can for example control a minimum age when we want to set an age, and many other simple examples.
Example:
setAge (int age)
{
if ( age < 0 )
{
System.out.println ( "Wrong age !!" );
}
}
Now I think you can easily understand this HW :)

Categories

Resources