i have two array
String a[]={"11","02","43","24","05","86","37","28","29","10"};
String b[]={"a","c","f","q","w","x","z","x","s","r"};
i want to sort array a[] in ascending order
and the result may like
String a[]={"02","05","10","11","24","28","29","37","43","86"};
String b[]={"c","w","r","a","q","x","s","z","f","x"};
how can i get result like above using java?
any sorting method available in java?
The easiest way would be to link the 2 pieces of data together in some way instead of having them in separate arrays. Many people have suggested a Map which would work great. Depending on exactly what you are trying to do, I would also consider a new class with 2 variables that implement Comparable. Comparable defines the natural ordering of a class when it is in a Collection (in this instance an array) if Collections.sort is not given a different Comparator to use. It would look something like this:
public class Data implements Comparable{
private String stringOne;
private String stringTwo;
#Override
public int compareTo(Object obj) {
stringOne.compareTo((String)obj);
}
Somewhere else call:
Collections.sort(locationOfDataCollection);
You could then create one Collection of Data and access the other String with a getter method. This implementation also would make it simple in future (see Strategy Design) if in some instances the natural order needed to be overridden with a new Comparator (e.g. sort by stringTwo).
Since you have 2 related sets of data, I would either link these via a Pair<String,String> type object and then into a List<Pair>, or put them into a Map<String,String>.
Perhaps the first solution is more intuitive e.g.
public class Pair implements Comparable<Pair> {
public String first;
public String second;
// equals/hashcode etc.
}
Once they're in a standard Java collection, numerous solutions exist for sorting these. e.g. in the above Pair I've implemented the Comparable<T> interface which the Collections sorting mechanisms will make use of.
There is no methods for directly doing this in Java. You have two options.
1) Define a Map<String, String>, put all the pairs in it (like ("11", "a")). Sort first array (or the keys of the map) and retrieve the elements of the map in that order.
2) Create an object that holds each par, create a List with it, and sort comparing only by the number (implement Comparable or create a Comparator).
One issue you'll need to be aware of is that Strings don't sort according to the same rules as integers. You are likely to be surprised by what you get if you leave the array by which you sort as String.
Related
I have 2 lists in java, and I need to validate when there is a match, I set a field of the first list, I tried to do it with streams, but I don't know how to compare the two lists, list don't have same kind of elements I want to do something like this:
public static List<TransactionalityIdDBDTO> getVariationDateRange(List<TransactionalityIdDBDTO> list1,
List<TransactionalityIdDBDTO> list2){
List<TransactionalityIdDBDTO> idDBDTOS= new ArrayList<>();
Iterator prueba=list1.iterator();
while(prueba.hasNext()){
TransactionalityIdDBDTO transactionalityIdDBDTO=(TransactionalityIdDBDTO) prueba.next();
if(transactionalityIdDBDTO.get_id().equals(list2.get_id())){
transactionalityIdDBDTO.setVariation("1232");
idDBDTOS.add(transactionalityIdDBDTO);
}
}
return idDBDTOS;
}
Clase TransactionalityIdDBDTO
public class TransactionalityIdDBDTO extends AbstractDTO {
private TransactionalityDBDTO _id;
private String totalTransaction;
private List<String> idResult;
private String variation;
You can compare lists using equals. e.g
list1.equals(list2);
However,
order is important. If lists contain the same content but in different order they will be considered unequal.
the objects the lists hold must override equals. The criteria for what constitutes two objects of TransactionalityIdDBDTO to be equal are up to you. Based on your code, it seems that id is a good start.
if you plan on using those objects as keys in a map, you must override hashCode too (it's a good idea to do this anyway).
if the lists are not in order but you want to consider them equal, then you should probably sort them first based on the id. You can do that like this.
list1.sort(Comparator.comparing(TransTransactionalityIdDBDTO::get_id));
list2.sort(Comparator.comparing(TransTransactionalityIdDBDTO::get_id));
Objects like String, Integer, and other wrapper classes implement Comparable which means they can be compared to each other of the same type using the above. But instead of get_id which returns a String, say you had get get_Foo. Then the Foo class would need to implement comparable or you would have to provide a more detailed comparator on which to sort.
There are many examples of Comparing objects on the site. I recommend you search them using the [hashCode], [equals], [comparable] and [comparator] tags. Imo, understanding these and how they work are essential for a reasonable working knowledge of Java.
ArrayList<ParkingList> Parkings = new ArrayList<ParkingList>();
ArrayList<ParkingList> ParkingsDB = new ArrayList<ParkingList>();
for example, Parkings may contain (a,b,c,d) objects and ParkingsDB may contain (a,b)
how can i find c,d
i tried using this method but it didint work,
ArrayList<ParkingList> temp = new ArrayList<ParkingList>(Parkings);
temp.removeAll(ParkingsDB);
my class definition:
public class ParkingList {
Rectangle R;
String Name;
int level;
String BuildingName;
public ParkingList(String BuildingName,String Name, Rectangle R, int level) {
this.R=R;
this.Name=Name;
this.level=level;
this.BuildingName=BuildingName;
}
}
i just wanna know, was my method that i used above a correct method? maybe i have another problem i need to fix.
my criteria is , two objects are equal only if all of the attributes in one object are the same in another object.
in order to utilise removeAll on a collection of custom types you'll need to provide an implementation of the equals method and if possible also the hashCode method as it is used by certain collections in the collection API.
another solution would be to utilise removeIf and specify the criteria which defines when two or more objects are equal.
e.g.
ArrayList<ParkingList> temp = new ArrayList(Parkings);
temp.removeIf(x -> ParkingsDB.stream()
.anyMatch(e -> e.getName().equals(x.getName())));
in this case, the criteria is when any given object in temp has the same name as any given object in ParkingsDB then it shall be removed from the temp list.
now you'll simply need to decide whether to provide your own implementation of equals and hashCode or utilise the example above; in all cases, you'll need to provide a criteria which defines when two given objects are equal.
This is irrelevant to the problem at hand, but you don't seem to respect the Java naming conventions at all.
variables as well as methods (except constructors which is a special type of a method) should start with a lowercase letter and follow the camelCase naming convention i.e rather than Parkings it should be parkings, rather than Name it should be name etc.
Also, you seem to have freely exposed the state of ParkingList. you should enforce encapsulation here by making all the variables private and only provide getters and setters where necessary.
The easiest way for you, as it was already mentioned - to implement ParkingList.equals() method. For example you can generate it by IDE.
Than your code:
temp.removeAll(ParkingsDB);
will work as you expected. This happens since list implementation basically depends on equals() method for checking elements.
You may also use streams:
ArrayList<ParkingList> temp = Parkings.stream()
.filter(parking -> !ParkingsDB.contains(parking))
.collect(Collectors.toList());
I need to store few data pairs in array. Maybe few dozens. I only need to append, no need to delete, no need to search. Then I will access by index. Each pair is String value and Integer value. Java provides so many way to do this, which is the common practice for something like that? Two arrays? A class in an array?
I know how to do this in JavaScript:
var data = []
data.push(['Some name', 100])
//somewhere else
data.push(['Other name', 200])
but I need a solution for Java
Thank you.
For example you can create Pair class (or use implementations from apache commons) to store two elements in List.
List<Pair<String, Integer>> l = new ArrayList<>();
l.add(new Pair<String, Integer>("Some name", 100));
See Generic pair class and Java Pair<T,N> class implementation to see how you can implement Pair class.
It really depends, but in general I think it is better to create an object and use a list of it:
public class MyObject {
private String myString;
private Integer myInt;
// getters setters
}
And use:
List<MyObject> = new ArrayList<>();
(you can also use Pair instead)
If the strings (or ints) are unique, you can use Map, but it is harder to get the insert index.
Another option is just two lists, one for Strings, one for Integers, and use same index in both lists.
I go by using POJO as suggested above for this as this helps to define getter and setter for all the attributes of POJO, compare the objects by overriding equals and hashCode methods. By using getter and setter you know what is stored in what field and comparison can provide you sorting of objects as per your requirements. So this approach is cleaner and extensible for accommodating new requirements too. Also as you are putting data with sequential key so each instance of Pojo can be put in List (if required in sorted order.
I have to implement a generic AVL tree as homework. It's defined as follows:
public class AVL<Key,Elem>;
The problem is that I assume that at some point, I'll have to compare keys to decide in which side of a node I allocate an element. For the purpose of this homework, Integers will be used as Keys.
Since no other restriction or information about that is given, I first thought of just asuming that Key will always be an Integer. However, that makes the generic "Key" superfluous, and I don't think that's what the teachers expect. So, I think that the best solution involves forcing that whatever that is passed as Key implements a Comparator, or something like that (I've really never worked with Comparator, just guessing), and then using that comparator to compare the Keys instead of using the ==,<,> and != operators. However, I have no idea on how to do it. Any hints?
Thanks in advance.
Try public class AVL<Key extends Comparable<Key>,Elem>; and use the compareTo() method which is required by the Comparable<T> interface and which is implemented by Integer.
The SortedMap and SortedSet implementations in the standard Java API either use a Comparator<Key> and call its compare(k1, k2) method, or assume the keys implement Comparable<Key>, and call k1.compareTo(k2). Most offer both, depending on which constructor is used. (EnumMap/EnumSet don't, as they support only the build-in ordering of the enum values by declaration order.)
The Comparable approach mandates that the keys are always sorted in the same way, and would be used for keys which have a canonical ordering (like integers), where you want to use this ordering.
The Comparator approach is more flexible, since you can use the same key objects for different maps where they are differently ordered, and you can use it for keys over which you have no control, or who don't have a canonical ordering (like List, trees/graphs, etc. You can also use it to sort strings keys by other criteria than the pure unicode value (e.g. Locale-based), using a Collator (this is a class implementing Comparator).
Both require a total order on your keys, but I suppose this is necessary for your AVL tree, too.
Here is a Comparator implementation which works on any comparable objects, so you could use it (maybe internally) as an adapter for the Comparable variant.
public static <X extends Comparable<X>> Comparator<X> makeComparator() {
return new Comparator<X>() {
public int compare(X left, X right) {
return left.compareTo(right);
}
};
}
Is it possible to search an array of objects in Java by a private attribute with the Array.binarySearch method? I was thinking there must be something similar to the sorting technique, where you create a class that implements Comparator and pass this in to Array.sort, but I can't seem to find anything (maybe there is something where instead of the compareTo method you just return the attribute used in the search)??
To be clear I have an array of anonymous Station objects, and this is passed to another class where I want to search the array for the name of the stations, which can be returned via a getName().
Any help would be much appreciated!
Yes - in fact it uses Comparator, which you specified in your answer!
If you have a look over the implementations of the binarySearch method in the API, you come across binarySearch(T[] a, T key, Comparator c) which:
Searches the specified array for the specified object using the binary search algorithm.
You can implement the Comparator however you like, and so can use it to compare the private attributes alluded to in your question.
Edit responding to comment: The T is a generic parameter, meaning it can be anything, so long as it's the same in every position it appears. In this case, it means that the first parameter must be an array of the second parameter's type. Or in other words, if you're sorting an array of Ts (Stations in your case) then you need to pass in an instance of that class (Station here) to act as the object to compare against. This key argument will always be passed in as one of the arguments to the comparator's compare method.
So I suspect in your case you were passing in a String representing the station name; you should instead pass in an instance of Station which has the appropriate name.
Yes, there's an overload that takes a comparator. Remember that you can only use binarySearch if the array is already sorted.
If the array of stations is not already sorted by the station names, it makes no sense sorting and searching for every query. It is faster to do a linear search in this case. However, if you can sort the array and then perform multiple binary searches, it is worthwhile. Implement a comparator such as the following, and use it for both sorting (Arrays.sort(..)) and searching (Arrays.binarySearch(..)):
private class StationNameComparator implements Comparator<Station> {
public int compare(Station s1, Station s2) {
return s1.getName().compareTo(s2.getName());
}
}
Note that I assume that the names are non-null and unique.
Thanks, eventually got it working using
Arrays.binarySearch(allStations,new Station("nameofstationhere"),new StationCompare())
which is probably a bad way as I'm creating a new Station object for comparison... but it works and not sure how to do it using just the string...