Ordering Array of Objects by an attribute [duplicate] - java

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 7 years ago.
Is There a java util method, or a short way to sort an Array of some type by an attribute of that type. I currently have an array of Choice type objects where each have a getText() method that returns the visual representation of the choice. I can make a long method that creates an array of the choices texts, sort them, get their ordered index and then order the choices by that index, but I surely think there is some kind of a shortcut.
Any Suggestions?

Collections.sort(list, new Comparator<Choice>(){
public int compare (Choise c1, Choice c2) {
return c1.getText().compareTo(c2.getText());
}
});
add check for null if necessary
you can move comparator to external class and use reflection to read custom field from any object. but this will make code less understandable

Related

How can I show a specific field of of a class I made when displaying an ArrayList? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I'm making a small program that simulates some of a bank's basic functions. I created a class Branch and used an ArrayList to hold Branch objects that the user would like to add. If I would like to specifically display all of the Branch names (one of the fields in the class) of each object contained in ArrayList<Branch>, would that be possible? Or is it better to create an array of strings that will hold each branch name? Currently, when I try to print out the ArrayList it outputs the pointer (I think) to the console.
I can put my code up upon request.
You basically answered it yourself. You just iterate over the ArrayList, and do stuff for each object.
For example, in a for-each-loop:
List<Branch> branchList = new ArrayList<Branch>();
for (Branch branch : branchList ) {
// iterates through all your objects contained in the list
// use the object here
}
Of course there are many more ways to do this, as it was already pointed out in a comment.
You need to iterate over your array to get the objects data.
Here is some example with Java 8 streams:
List<Branch> branches = new ArrayList<Branch>();
// prints out the name of the object
branches.stream().map(branchName -> branch.getName()).forEach(System.out::println);
I found a nice blogpost which explains streams and how you can work with it. In my opinion the best way to work with Lists:
https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

ArrayList object sorting by integer [duplicate]

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 4 years ago.
So I've made an ArrayList of Catalogue Entries, where CatalogueEntry is made up of an int, a string and a status (which has been previously defined). I want to order the elements of the list (aka the Catalogue Entries) according to their integer. Is there any way I can do this?
Yes there is, but you must tell the program what do you mean by saying that one CatalogueEntry is bigger then an other. There are multiple ways of doing this but one example is the Comparable interface
public class CatalogueEntry implements Comaparable<CatalogueEntry> {
private int yourInt;
//methods, variables here
#Override
public int compareTo(CatalogueEntry other){
if(this.yourInt == other.yourInt) return 0;
if(this.yourInt > other.yourInt) return 1;
return -1;
}
As you can see you must implement the compareTo method and return 0 if the other entry is equal to this, -1 is its bigger and 1 if it's smaller! This way the program will know how to sort these objects and you can just use the ArrayList's sort method!
Using Comparable and Comparator you can do this. This example will give you a clear idea of how to sort your list by a property of an object. In this example Student objects are sorted by their age.
example

Is it possible to perform an operation on an object in a Hashset without iteration [duplicate]

This question already has answers here:
Why doesn't java.util.HashSet have a get(Object o) method?
(11 answers)
Closed 4 years ago.
If there any way we can call the method of an object inside a Hashset which in itself is a value in a Hashmap without making an iterator or a .forEach(lambda) or in any way going through each object sequentially?
Consider we have a Hashmap like this. Map<Boolean,Set<Place>> selectedMap
Consider Place extends JComponent and has a boolean value representing if the user had selected the object with the mouse, the map contains a set with all selected and all unselected objects.
If we for example want to call the remove-method of all selected objects, is there a way of doing that in the manner outlined above?
If you want to call a method for all the elements in a Set, you must iterate over the elements of that Set.
That said, instead of an explicit loop, in Java 8 you can use the forEach method:
selectedMap.get(true).forEach(Place::remove);
or
selectedMap.get(true).forEach(place -> place.remove(...));
in case the remove() method requires some arguments.

Hashset Containg duplicate values ; Also ArrayList indexOf(string_present_in_list) returning -1 [duplicate]

This question already has answers here:
A Set in java never allows duplicates, but it takes StringBuffer objects with the same argument. Why?
(6 answers)
String Vs Stringbuffer as HashMap key
(4 answers)
Can a StringBuffer be used as a key in a HashMap?
(4 answers)
Closed 5 years ago.
I have made a Hashset of StringBuilder.
The below code returns "true" even if that StringBuilder is present in Hashset:
if(!contains(sb_obj))
{
...
}
Also I have made a ArrayList of StringBuilder.
The below code returns "-1" even if ArrayList contains obj:
if(arr.indexOf(obj)==-1)
{
....
}
Why such behaviour?
I assume you are comparing different StringBuilder objects that have the same String values.
StringBuilder doesn't override equals and hashCode methods. This causes HashSet and ArrayList to use Object's implementation of them which compares by identity. Since you are comparing different objects they are different.
Please use String instead of storing StringBuilder object or if you want to store custom object override hashcode and equals methods whenever you are trying to add and search back that object.
Please read the concept of hascode and equals method, you can find many examples over internet.

ArrayList vs Vector [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are the differences between ArrayList and Vector?
I've been using Vectors quite a lot in my recent program. However I've read somewhere that Vectors are a bit old. Whether that means it will be obsolete or phased out of Java is debatable. So the recommendation was that ArrayLists should be used instead. I've noticed that ArrayLists don't have a method remove(int index, Object object) while vectors do. The reason I ask is suppose I add a string, say "String 1". And I attempt to add the same string again. How do I remove the first string without counting the occurrences of it in an array list.
However I've read somewhere that Vectors are a bit old : Yes vector class is considerd as legecy and is still in library to support old applications. It is replaced by Collections.synchronizedList(list) .
I've noticed that ArrayLists don't have a method remove : You can remove the data based on Index. if u want to remove the object use boolean java.util.ArrayList.remove(Object o) : dont forget to override the equals and hashcode method :)
How do I remove the first string without counting the occurrences of it in an array list : Best thing is to use set. If thread safty is a concern use <Object> Set<Object> java.util.Collections.synchronizedSet(Set<Object> s)
Hope all your questions are clarified.
Regards,
Punith

Categories