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.
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.
Is there a data structure in Java which can hold more than 4 values?
So something along the lines of
Map<String, String, String, String>;
This is needed to be able to reduce the number of if else statements I have. I would like to be able to do the following.
check if the data structure contains an element which matches a certain value, if it does then it assigns a link(which is string) to a variable and then adds a code and message to another variable which is related to that link.
if not is there a good workout around to achieve this?
Is there a data structure in Java which can hold more than 4 values?
There are lots of them.
The simplest is probably String[] which can hold 4 strings if you instantiate it like this:
new String[4]
And other Answers give other data structures that might meet your actual (i.e. unstated) requirements.
However, it is probably possible ... let alone sensible ... for us to enumerate all of the possible data structures that can meet your stated requirement.
Hint: you should try to explain how this data structure needs to work.
Hint 2: "the lines of Map<String, String, String, String>" does not help us understand your real requirement because we don't know what you mean by that.
UPDATE - Your explanation is still extremely vague, but I think you need something like this:
Map<String, MyRecord>;
public class MyRecord {
private String link;
private String code;
private String message;
// add constructor, getters, setters as required
}
There is nothing in the standard libraries, but Guava has a nice implementation; called
Multimap
If Guava is not an option in your environment, you will have to re-invent the wheel though.
Use can use MultiMap on Apache,
A MultiMap is a Map with slightly different semantics. Putting a value into the map will add the value to a Collection at that key. Getting a value will return a Collection, holding all the values put to that key
MultiMap mhm = new MultiValueMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);
Use Map of map:
Map<String, Map<String, Map<String, String>>>
Reading your question, It seams like you simply need a 'key-value' pair. Key being a 'String', which you have referred as 'a certain value' in your question. Value is a kind of wrapper object wrapping three Strings which you have referred as 'link, code and message'.
I suggest you can simply use
HashMap < String, Wrapper > map;
You can create a class ' Wrapper.java' which can contain three Strings, as instance fields
String link,code,message;
You can instantiate these fields in constructor and later can retrieve them using getter methods or also can have setters to set the values you need. You can provide a better contextual name to the class 'Wrapper.java'.
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.
I am looking to implement a data structure that would add / render an ordered pair of values. eg.
orderedPair.add(value1, text1)
orderedPair.add(value1, text2)
orderedPair.add(value2, text3, data1)
orderedPair.add(value2, data2)
orderedPair.add(value1, text5)
When I get, I want it to return iteratively as
value1, text1
value1, text2
value2, text3, data1 and so on.
LinkedHashMaps or any variants of HashMaps do not work since they return only the value based on key and what I am trying to get is value, value pairs. Note that neither value / text or data are unique and I may not be able to fetch it based on any keys. Also, i do NOT want a sorted list, I do need an ORDERED list only.
Question is: Is there any data structure in Java that can be used to accomplish this?
I did not come across any that serves this purpose. In which case I am pondering about writing a custom collection that would accomplish this. Any suggestions / help is welcome.
Wrapping the discussion in the comments into an answer, since it seems to be useful to the OP:
Create a class Tuple, which will be your pairs/triples.
Note that this class can be implemented with a fixed number of parameters or as a container that holds a list of objects.
Hold these Tuple objects in a List<Tuple>, and you are done.
You can also implement hashCode(), equals() and make it implement Comparable to this class - and you will be able to use it with other collections such as TreeSet and HashSet.
Just use a Map of Lists, like Treemap
Map<Integer, List<Integer>> content = new Treemap<Integer, List<Integer>>();
if (not content.containsKey(value1)) {
content.put(value1, new LinkedList<Integer>());
}
content.get(value1).add(text1)
This would be the function orderedPair.add
Then for output, traverse the Map and for each entry, write out each item of the corresponding List
Since you want to have it ordered, pass a Comparator to the Treemap constructor.
I have this type ArrayList<HashMap<String,String>> . I want to check if a key exist in that array list . I can do this through a for loop but is there any alternative way to do this ?
While building those individual HashMaps, if you could build a super hashmap, then there is no need for for loop. But don't know if it is possible for you. Just look-up in that super-hashmap.
Along the line of #Bhushan's answer, create a new class that encapsulates the ArrayList of maps, and a Map of the key values. E.g.
public class EncapsulatedLookup {
private ArrayList<HashMap<String,String>> data;
private Map<String, Integer> keyToArrayListPosition lookup;
}
Add methods to ensure whenever you add/remove from data, you also update the lookup
The most easiest way that comes into my mind and maight work is to extend the HashMap class and implement .equals() method. Anyway, this method also internally uses interation.