I need to write a setter for an array using spring's value annotation so it will come from properties file.
private String[] aList;
public String[] getAList()
{
return aList;
}
#value("a:b")
public String[] setAList(String aString)
{
aList = aString.Split(":");
}
I am not sure if this is the right way to do?
Will I get the right value from string?
Thanks,
Always have the same type for getter and setter pairs. In order to perform what you want, you could simply rename setAList to setAListAsColonSeparatedValues or something similar. Also, your setter method should return void.
If you put them in your properties file as
listItems=1,2,3,4,5,6
Spring will load an array for you
#Value( "${listItems}")
private String[] aList;
If iterate through aList you get
item = 1
item = 2
item = 3
Related
I can use the below snippet to retrieve the name if there is 1 entry in the list by retrieving element 0 in the list, however, each NameResponse can have several names (e.g. a first name, a middle name and a surname). How can I retrieve x names associated with one customer? There could be 20 names for argument's sake. I would like to implement using a stream since I am using Java 8, but I am unsure how to implement this. Any suggestions?
private List<String> getNames(Customer customer) {
List<NameResponse> nameResponses = new ArrayList<>();
NameResponse nameResponse = new NameResponse();
nameResponse.setName("Test Name");
nameResponses.add(nameResponse);
customer.setNames(nameResponses);
return List.of(customer.getNames().get(0).getName());
}
Customer class:
private List<NameResponse> names;
NameResponse class:
private String name;
Something like below assuming you have the appropriate getters:
return customer.getNames()
.stream()
.map(NameResponse::getName)
.collect(Collectors.toList());
You could do that using the map operator on the stream and then collect to output a list:
return customer.getNames().stream()
.map(nameResponse -> nameResponse.getName())
.collect(Collectors.toList()));
I have a huge group of keys like more than 10L like the below in csv file
ABA,100
ABC,200
ABCs,50
ABM,65
ABMs,86
ABS,86
AC,54
ACLU,123
ACT,56
ACTH,154
AD,644
ADC,76
ADD,10.
Do I need to create the user define an object for the above key pairs? Will it create any memoery problem for creating more than 10L user define object?
My input String looks like [ABS,AC,ACLU,ABC]
I want the output AC,ABS,ACLU,ABC based on the count.
How to achieve it in easier way of Java 1.8.
Thanks.
You could add each line of your csv to a List<String> myList
Then, you will have to create a custom Comparator in order to sort your list based on the value, so something like the following,
private void customSorting(List<String> myList) {
Collections.sort(myList, (String s1, String s2) -> {
String valuePart1 = s1.split(",")[1];
String valuePart2 = s2.split(",")[1];
return Integer.valueOf(valuePart1).compareTo(Integer.valueOf(valuePart2));
});
}
Finally, just call your method like customSorting(myList); in any place of your code you need it
Of course, you have to modify the sorted list as well to keep only the first part (before comma) for each String value but that's easy.
An alternative could also be to create a class like the following,
public class MyClass {
private String key;
private String value;
// All the getters, setters, constructors, etc
}
, and then read each line of your csv, create an equivalent MyClass POJO and add it to a List<MyClass> myList.
You have to write your own custom Comparator again for List<MyClass> in a similar way like I did for the List<String>,
private void customSorting(List<MyClass> myList) {
Collections.sort(myList, (MyClass a, MyClass b) -> {
return Integer.valueOf(a.getValue()).compareTo(Integer.valueOf(b.getValue()));
});
}
Finally, create a new list from the sorted one by keeping only the keys
I am to using asserThat to verify properties of objects in an ArrayList.
I am able to use assertThat if none of the objects contains data to be tested but I am not able to figure how to use assertThat if only one of the objects contain data to be tested.
Sample Code:
public class dataNeeded {
String data;
String modifiedDate;
public String getData(){
return data;
}
......
}
public ArrayList<dataNeeded> returnsNeededData(){
...
}
List<dataNeeded> dataToBeTested = returnsNeededData();
dataToBeTested.forEach(data->assertThat(data.getData(), not(equalTo("No"))));
List<dataNeeded> dataToBeTested2 = returnsNeededData();
// I need to verify if one of the objects in this list has it's data as "No"
dataToBeTested.forEach(data->assertThat(data.getData(), ???);
You can map to List<String> via the following function (uses Java 8 Streams) to extract all data strings
private List<String> mapToDataStrings(List<dataNeeded> neededData) {
return neededData.stream()
.map(dataNeeded -> dataNeeded.getData())
.collect(toList());
}
and then use the everyItem/hasItem function in Matchers to make assertions on the resulting list of strings:
List<String> dataToBeTested = mapToDataStrings(returnsNeededData());
assertThat(dataToBeTested, everyItem(not("No")));
List<String> dataToBeTested2 = mapToDataStrings(returnsNeededData());
assertThat(dataToBeTested2, hasItem("No"));
With everyItem you can assert that every element in the list is not "No" and hasItem asserts that there is at least one element in the list with value "No".
Alternatively you could implement a feature matcher to avoid the mapping function.
I have two different methods which fetch data from tow different DB tables. I will add both data into same ArrayList using bean class.
List<LeadVO> leadvoList = new ArrayList<LeadVO>(); // array list declaration
In the while loop I will load all the data using bean class. Before this action I will fire query for both tables.
while(true){
LeadVO statusVO = new LeadVO(); //initializing bean class
// code to load all value using setters
Finally I will add this bean to array list:
leadvoList.add(statusVO);
created seperate class to compare
public class ComparatorDAO implements Comparator {
public int compare(LeadVO arg0, LeadVO arg1) {
return arg1.getCreatedtimeFormat().compareTo(arg0.getCreatedtimeFormat()) ;
}
}
Collections.sort(commentVOList,new ComparatorDAO()); //sorting method
ideally this will not sort according to date i believe this will treat date as string
please help me in this
thanks once again
Now I need to sort this list in date order which is already present in the list. I mean the date which is present in the list.
If your LeadVO contains the date you want to sort by, implement Comparable interface in your VO and then sort the VO collection using Collections.sort().
public class LeadVO implements Comparable<LeadVO> {
private Date date;
// other properties, getters and setters
#Override
public int compareTo(LeadVO other) {
return date.compareTo(other.getDate());
}
}
and the sort like this:
Collections.sort(leadVoList);
You should ideally add null checks or use something like ObjectUtils.compare from commons-lang if your date is not guaranteed to be non-null.
Also you could do this by creating a Comparator instead of implementing Comparable as suggested by other posters, which might be better if you need to sort your VO by multiple values. If you just need to sort it by date, this approach might be a little simpler.
Here is the Example:Hope you don't mind hard interpretation.
List<String> unsortList = new ArrayList<String>();
unsortList.add("CCC");
unsortList.add("111");
unsortList.add("AAA");
unsortList.add("BBB");
unsortList.add("ccc");
unsortList.add("bbb");
unsortList.add("aaa");
unsortList.add("333");
unsortList.add("222");
//before sort
System.out.println("ArrayList is unsort");
for(String temp: unsortList){
System.out.println(temp);
}
//sort the list
Collections.sort(unsortList);
//after sorted
System.out.println("ArrayList is sorted");
for(String temp: unsortList){
System.out.println(temp);
}
}
You can sort arrayList using a comparator:
public Comparator<Record> RecordComparator = new Comparator<Record>() {
public int compare(Record record1, Record record2) {
return record1.getDate().compareTo(record2.getDate());
}
};
and then:
Collections.sort(list, new RecordComparator());
U'll need to override that class compareTo method as it is the method which java looks at for sorting
Simply override the fields that u need sorted
compareTo(Object other){Someclass.somefield.compareTo(other.smeField)}
Is it possible to store a list of integers in a single field of the respective entity table with standard JPA 2?
#Entity
#Table(name="tbl_myentities")
public class MyEntity {
#ElementaryCollection
#Column(name="vals") // in table tbl_myentities
private List<Integer> vals;
It is not possible to store multiple values in a single field. Whats the reason behind storing them in a single field?
A way could be to use a field of type String and add all integers there in a comma separated list and join/explode in getters and setters:
private String vals;
public setVals(int vals[])
{
// this.vals = Iterate vals[] and create a comma separated string
}
public int[] getVals()
{
// vals.split(",") to get a list of Strings, then typecast/parse them to ints before returning
}
Using the #ElementCollection annotation and #CollectionTable to control the mappings requires a separate table to store the values in.
#ElementCollection
private Collection<Integer> integers;
Read more about element collections on on http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
Similar question here Does JPA #ElementCollection annotation always produce an one-to-many relationship?
You can create a converter and use it with the annotation #Converter.
This converter must implement AttributeConverter which is a generic interface with two methods convertToDatabaseColumn and convertToEntityAttribute.
It is pretty easy to work with, you can check here: jpa independent custom type mapping / javax.persistence.x alternative to org.hibernate.annotations.Type and org.hibernate.annotations.TypeDef
You can store all the vals in a String field, separated with a comma, and change associated getter and setter like that :
public List<Integer> getVals() {
List<Integer> lstVals = new ArrayList<Integer>();
int val = 0;
for(String field : this.vals.split(",")) {
try {
val = Integer.parseInt(field);
}
// If the String contains other thing that digits and commas
catch (NumberFormatException e) {
}
lstVals.add(val);
}
return lstVals;
}
public void setVals(List<Integer> vals) {
String newVals = "";
for(int i : vals) {
newVals.concat(String.valueOf(i));
}
this.vals = newVals;
}
I don't think that's possible. Because you can not have a column in a database table that allows you to store list of integers.
What you can do is use a string type field instead of list of integers -
#Column(name="vals") // in table tbl_myentities
private String vals;
And do the conversion to string from list of integers and back manually before you save your entity and after you have read your entity.
Maybe a #Lob could suit you ? (despite what it imply)
#Lob
ArrayList<String> vals;
(note that your collection must be explicitly an ArrayList)