I want to do something like this
List<Integer, String, String>
I want to be able to iteratively retrieve either of these three parameters. How can I go about it? Thanks
I want to do something like this
List<Integer, String, String>
I want to be able to iteratively retrieve either of these three parameters. How can I go about it? Thanks
What you need is a Tuple class:
public class Tuple<E, F, G> {
public E First;
public F Second;
public G Third;
}
Then you can iterate over the list of the tuple, and look at each entry in the tuple.
List<Tuple<Integer, String, String> listOfTuple;
for (Tuple<Integer, String, String> tpl: listOfTuple){
// process each tuple
tpl.First ... etc
}
You can create a wrapper class which holds these three variables and then store that wrapper-object in the list.
For instance
public class ListWrapperClass {
private String firstStringValue;
private String secondStringValue;
private Integer integerValue;
public String getFirstStringValue() {
return firstStringValue;
}
public void setFirstStringValue(String firstStringValue) {
this.firstStringValue = firstStringValue;
}
public String getSecondStringValue() {
return secondStringValue;
}
public void setSecondStringValue(String secondStringValue) {
this.secondStringValue = secondStringValue;
}
public Integer getIntegerValue() {
return integerValue;
}
public void setIntegerValue(Integer integerValue) {
this.integerValue = integerValue;
}
}
and then use List<ListWrapperClass>.
You can use a List<Object> and then cast whatever you retrieve based on the index, but you may just consider creating a class that holds these three things.
List<Object> should be avoided when possible.Another alternative is to use a Tuple from a dependency in Maven central repo
<dependency>
<groupId>org.javatuples</groupId>
<artifactId>javatuples</artifactId>
<version>1.2</version>
</dependency>
You then create an object with two or more types like this:
Pair<String, Integer> person = new Pair<>("John", 50);
Triplet<Integer, String, String> person1 = new Triplet<>("John", 50, "single")
There are 10 types of tuples, each for a corresponding number of items:
Unit (one element)
Pair (two elements)
Triplet (three elements)
Quartet (four elements)
Quintet (five elements)
Sextet (six elements)
Septet (seven elements)
Octet (eight elements)
Ennead (nine elements)
Decade (ten elements)
And then you can just use it in a list like any other type.