I have got class:
class Region{
String name;
List<String> BlockPlayers = new ArrayList<>();
}
Then I made a List of objects in my program like this
List<Region> playersRegions = new ArrayList<>();
Now I need to make a function that will pass objects from playersRegions list to config file. Then I need to make function that will load everything from config file and pass to playersRegions list
I have made something like this
private void save_regions_inConfig()
{
getConfig().set("locs", playersRegions);
saveConfig();
}
But I have no idea how to load it from file to playersRegions. I just want to keep everything after I close the program and open it once more.
You should define a way to format the region.
Let assume method are on your JavaPlugin class and everything else is well made (plugin.yml valid etc)
To write them, use something like this:
public void saveRegion(List<Region> regions) {
FileConfiguration config = getConfig();
int i = 0;
for(Region r : regions) {
config.set("regions." + i + ".name", r.name);
config.set("regions." + i + ".blockplayers", r.BlockPlayers);
i++;
}
saveConfig();
}
The config file will be like this:
regions:
0:
name: "Region 1"
blockplayers:
- "Something"
Now, to read it, you should do something like that:
public List<Region> getRegion() {
ConfigurationSection config = getConfig().getConfigurationSection("regions");
if(config == null) // no region set yet
return new ArrayList<>();
List<Region> list = new ArrayList<>();
for(String keys : config.getKeys(false)) {
ConfigurationSection regionConfig = config.getConfigurationSection(keys);
list.add(new Region(regionConfig.getString("name"), region.getStringList("blockplayers")));
}
return list;
}
Note: you should define a constructor in your Region object like that:
public class Region{
String name;
List<String> blockPlayers = new ArrayList<>();
public Region(String name, List<String> blockPlayers) {
this.name = name;
this.blockPlayers = blockPlayers;
}
}
Finally, some of your name (method or variable) doesn't meet the Java convention. Specially about method, but that's a detail.
This should work
public List load_playerRegions_fromConfig(List<Region> playersRegions) {
return getConfig().getList("locs", playersRegions);
}
Related
I created an object N, which has some attributes, like this:
public class LogEvidence {
private String comment;
private String url;
private String time;
public LogEvidence(String comentario, String url, String tiempo) {
super();
this.comment = comentario;
this.url = url;
this.time = tiempo;
}
public String getComentario() {
return comment;
}
public void setComentario(String comentario) {
this.comment = comentario;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTiempo() {
return time;
}
public void setTiempo(String tiempo) {
this.time = tiempo;
}
#Override
public String toString() {
return "LogEvidence [comentario=" + comment + ", url=" + url + ", tiempo=" + time + "]";
}
}
Now I want to do something like this:
ArrayList<LogEvidence>log = new ArrayList<LogEvidence>();
I want go through the list and add all the attributes to my object, I mean something like this:
log.setComment("comment one");
log.setUrl("http://google.com");
log.setTime("04:20");
Maybe this is not possible and I have to do something like the following?
List list= new List();
LogEvidence object1= new LogEvidence ();
object1.setComment("comment");
object1.setUrl("http://url.com");
object1.setTime(20);
lista.add(object1);
This is how you can do it:
Create an object of LogEvidence.
LogEvidence logEvidence = new LogEvidence();
logEvidence.setComentario("comment one");
logEvidence.setUrl("http://google.com");
logEvidence.setTiempo("04:20");
and add it into the array list.
log.add(logEvidence);
So, you can then create more objects and keep putting in the list. Since your list is named as log, so that is why you will add in log
Explaining it a little more, it should be something like this:
List<LogEvidence> logEvidenceList = new ArrayList<>();
LogEvidence logEvidence1 = new LogEvidence();
logEvidence1.setComentario("comment one");
logEvidence1.setUrl("http://google.com");
logEvidence1.setTiempo("04:20");
logEvidenceList.add(logEvidence1);
LogEvidence logEvidence2 = new LogEvidence();
logEvidence2.setComentario("comment one");
logEvidence2.setUrl("http://google.com");
logEvidence2.setTiempo("04:20");
logEvidenceList.add(logEvidence2);
....
....
....
Or through constructor call, this will become more concise and readable.
List<LogEvidence> logEvidenceList = new ArrayList<>();
LogEvidence logEvidence1 = new LogEvidence("comment one","http://google.com","04:20");
logEvidenceList.add(logEvidence1);
LogEvidence logEvidence2 = new LogEvidence("comment one","http://google.com","04:20");
logEvidenceList.add(logEvidence2);
....
....
....
Now, when you want to retrieve objects from the list, you can traverse the list and get one by one like;
for (LogEvidence evidence : logEvidenceList) {
System.out.println(evidence);
}
For more information about ArrayList
As Kon commented, you are trying to act upon an object that will be within the list, rather than the list itself.
There are a few ways to do this, but since you have a parameterized construtor, the easiest would be this:
ArrayList<LogEvidence> log = new ArrayList<LogEvidence>();
log.add(new LogEvidence("comment one", "http://url.com", "04:20");
What's being done:
We create the list with new ArrayList<LogEvidence>() and assign it to a variable called log.
Then, we create a new LogEvidence object, already assigning it's data through it's constructor's parameters, with new LogEvidence("comment one","http://url.com","04:20").
Since it will be stored in the list, we can use it anonymously. We add it to the list directly, using the list's .add(E e) method, rather than assigning it to a variable.
You don't need to define or assign unnecessary variables, in this case.
And if you need to access any specific LogEvidence from the list, you can use the .get(int index) method. In this case, log.get(0), to return the first element, would return the object you just inserted in the example code above.
You can also use a FOR-EACH LOOP to act upon all objects in the list, in iterating manner. Here is an example that prints the list:
for (LogEvidence evidence : log) {
System.out.println(evidence);
}
i have a domain class(DB):
public class PersonDoamin {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
i also have model class:
public class PersonBean extends PersonDoamin {
}
so when i go to DAOImpl class and query for List and transfer this list to List and return to users as i have interface method for List getAllPerson(). so my questions is here when i transfer all data from List. Here i have some utility method that copies from one bean to another like this:
List<PersonDoamin> list = PersonDAO.getAllPersons();
List<PersonBean> pbList = new ArrayList<PersonBean>();
/* this below logic is pretty much in the all DAO impl*/
for(PersonDoamin p : list){
PersonBean pb = new PersonBean();
CopyHelper.copyBean(p, pb);
pbList.add(pb);
}
return pbList;
can we replace the looping and copying and adding to another list and returning part with somekind of generic method which will take any object two list and loop thorugh one and add it to another passed List parameter and return it. something like below which is not perfect right now:
public static <T> List<T> listToArray(List<T> list,List<T> list2) {
for(T element : list){
list2.add(element);
}
return list2;
}
public static void main(String[] args) {
List<PersonDoamin> personList = new ArrayList<PersonDoamin>();
PersonDoamin p = new PersonDoamin();
p.setName("aj");
p.setAge("25");
personList.add(p);
List<PersonBean> personBeansToReturn = new ArrayList<PersonBean>();
Test.listToArray(personList , personBeansToReturn );
}
A bit off topic, your design seems a bit weird that you have "Domain" class and "Bean" class and have "Bean" extends "Domain"...
Anyway, come back to your question, what you are trying to do is:
You have a List<Domain>
You want to transform each Domain in the List into a Bean (by use of some util method)
Put the resulting Beans into a list and return
Let's go through it step by step.
(by the way, the listToArray method you wrote does not align with your original loop as it does not do the transformation (point 2). I guess it is typo?)
(all psuedo code as I don't have environment on hand to make it compile. Concept should be correct I guess)
Step 1: Util method for Person
One biggest problem of your original util method is that, it is illegal to put a Parent object instance to a List of Child (it should be easy to figure why by yourself).
The util method should look like this:
List<PersonBean> toBeans(List<PersonDomain> domains) {
List<PersonBean> beans = new ArrayList<>(domains.size());
for (PersonDomain domain: domains) {
PersonBean bean = new PersonBean();
CopyHelper.copyBean(domain, bean);
beans.add(bean);
}
return beans;
}
Step 2: Make it generic
The problem above is that it only works for Person. If you want to make it generic, you will also need to provide the function to transform Domain to Bean:
(Assume you are using Java8, should be trivial to make your own interface if you are using older version)
<D,B> List<B> toBeans(List<D> domains, Function<B,D> mapper) {
List<PersonBean> beans = new ArrayList<>(domains.size());
for (PersonDomain domain: domains) {
beans.add(mapper.apply(domain));
}
return beans;
}
so that you can use it by:
return toBeans(personDomains, (domain) -> {
PersonBean bean = new PersonBean();
CopyHelper.copyBean(domain, bean);
return bean;
});
(You may consider wrap the function if in most case you are going to use the CopyHelper way)
<D,B> List<B> toBeansByBeanCopy(List<D> domains, Class<B> beanClass) {
return toBeans(domains, (domain)-> {
B bean = beanClass.newInstance();
CopyHelper.copyBean(domain, bean);
return bean;
});
}
so that you can use it as
return toBeansByBeanCopy(personDomains, PersonBean.class);
Step 3: Java has done it for you
Actually what you are trying to do above, it is already provided by Java in Java 8. You can simply do:
return personDomains.stream()
.map(d -> {
PersonBean bean = new PersonBean();
CopyHelper.copyBean(domain, bean);
return bean;
})
.collect(Collectors.toList());
You may write a little method to use in the lambda expression if it is the standard way.
return personDomains.stream()
.map(BeanMapper.mapper(PersonBean.class))
.collect(Collectors.toList());
(Leave the implementation as your exercise)
If you're looking for a way to call new on a generic type, you can, sort of. You have to use reflection and call newInstance on the Class object. I don't know if this is going to be feasible for you.
Also, I don't see anyway of realistically implementing your bean copy method without using some heavy reflection as well. In the example below I faked by just casting to the required classes.
public class GenericCopyTest
{
public static void main( String[] args ) throws Exception
{
List<PersonDoamin> personList = new ArrayList<PersonDoamin>();
PersonDoamin p = new PersonDoamin();
p.setName( "aj" );
p.setAge( "25" );
personList.add( p );
List<PersonBean> personBeansToReturn = new ArrayList<PersonBean>();
copyAndDowncast( personList, personBeansToReturn, PersonBean.class );
System.out.println( personBeansToReturn );
}
public static <T,U extends T> List<U> copyAndDowncast( List<T> from,
List<U> to, Class<U> type )
throws InstantiationException, IllegalAccessException
{
for( T element : from ) {
U nu = type.newInstance();
copyBean( element, nu );
to.add( nu );
}
return to;
}
private static <X,Y extends X> void copyBean( X from, Y nu ) {
((PersonBean)nu).setName( ((PersonDoamin)from).getName() );
((PersonBean)nu).setAge( ((PersonDoamin)from).getAge() );
}
}
class PersonDoamin {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
#Override
public String toString()
{
return "PersonDoamin{" + "name=" + name + ", age=" + age + '}';
}
}
class PersonBean extends PersonDoamin {
#Override
public String toString()
{
return "PersonBean{" + getName() + ',' + getAge()+ '}';
}
}
Output:
run:
[PersonBean{aj,25}]
BUILD SUCCESSFUL (total time: 0 seconds)
Why not just use addAll() for this? It does what you're trying to do, and it's already part of the system library.
Remember you can add a PersonBean to a PersonDomain list, but not the other way around.
public class GenericCopyTest
{
public static void main( String[] args ) {
List<PersonDoamin> personList = new ArrayList<PersonDoamin>();
List<PersonBean> personBeansToReturn = new ArrayList<PersonBean>();
personList.addAll( personBeansToReturn );
personBeansToReturn.addAll( personList ); // <-- FAILS
// No suitable method found
}
}
class PersonDoamin {}
class PersonBean extends PersonDoamin {}
If you want to put more than one bean class in the same list,
how about creating the list with parent class PersonDoamin , and then, you can store both PersonDoamin and PersonBean classes.
public static void main(String[] args) {
List<PersonDoamin> personList = new ArrayList<PersonDoamin>();
PersonDoamin p = new PersonDoamin();
p.setName("aj");
p.setAge("25");
personList.add(p);
// Changed here. PersonBean => PersonDoamin
List<PersonDoamin> personBeansToReturn = new ArrayList<PersonDoamin>();
Test.listToArray(personList, personBeansToReturn);
// also you can insert PersonBean into the list
personBeansToReturn.add(new PersonBean());
}
I would like to know if there is a way I can access examples table row data within a step method without passing it in as an argument?
Story file:
Given I am logged in
When I create a trade
Then a trade should be created
Examples:
|data1|data2|
|11111|22222|
|33333|44444|
Step file:
#When("I create a trade")
public void createTrade(#Named("data1") String data1, #Named("data2") String data2){
//code to create trade using data1 and data2
}
Above works fine, but I would like a way to access the data row from the examples table within the method. (The reason I would like to do this is because all columns may not be present in the examples table in every story, and I have found that if I have say 3 * #Named as parameters in the step method, but one of these are missing from the actual examples table then it fails to run.)
#When("I create a trade")
public void createTrade(){
//check if there is a data1 column, if so get value and do something
//check if there is a data2 column, if so get value and do something
}
Thanks for your help
You can implement a new parameter converter, and then pass the table as an object.
for example, in our project we built ExamplesTableConverter (note: there is an our of the box JBehave converter that we didn't test):
public class ExamplesTableConverter extends ParameterConverters.ExamplesTableConverter {
private final ExamplesTableFactory factory;
private static final String ROW_SEPARATOR = "\n";
private static final String FIELD_SEPARATOR = "|";
public ExamplesTableConverter(){
this(new ExamplesTableFactory());
}
public ExamplesTableConverter(ExamplesTableFactory factory){
this.factory = factory;
}
#Override
public boolean accept(Type type) {
if (type instanceof Class<?>){
return ExamplesTable.class.isAssignableFrom((Class<?>) type);
}
return false; //To change body of implemented methods use File | Settings | File Templates.
}
#Override
public Object convertValue(String tableAsString, Type type) {
System.out.println(tableAsString);
String[] rows = tableAsString.split(ROW_SEPARATOR);
StringBuffer resultString = new StringBuffer();
resultString.append(rows[0]);
resultString.append(ROW_SEPARATOR);
for(int i=1; i<rows.length; i++){
String originRow = rows[i];
List<String> rowValues = TableUtils.parseRow(originRow, FIELD_SEPARATOR, true);
String translatedRow = translateRow(rowValues);
resultString.append(translatedRow);
resultString.append(ROW_SEPARATOR);
}
System.out.println(resultString.toString());
Object table = factory.createExamplesTable(resultString.toString());
return table;
//return null;
}
private String translateRow(List<String> rowValues) {
StringBuffer result = new StringBuffer(FIELD_SEPARATOR);
for(String field : rowValues){
try{
result.append(translate(field));
result.append(FIELD_SEPARATOR);}
catch (LocalizationException e){
e.printStackTrace();
//Need do something here to handle exception
}
}
return result.toString();
}
}
then you need to add that converter to your configuration:
configuration.parameterConverters().addConverters(new ExamplesTableConverter());
create a method that use it
#When("create parameters of type $param1 from the next table: $table")
public void doThis(#Named("param1") String param1, #Named("table") ExamplesTable table)
and last, use it in a story:
When create parameters of type type1 from the next table:
|FirstName|LastName|
|Donald|Duck|
this would allow you to iterate the table.
following blog post can also help you
Simpler JBehave Examples Table Processing
Scenario:-
Given data insert in DemoSheet
|demoNumber|demoName|
|101|Demo1|
|102|Demo2|
|103|Demo3|
|104|Demo4|
|105|Demo5|
java class to fetch value from scenario:-
#Given("data insert in DemoSheet $parameterTable")
public void setDataToSheet(ExamplesTable parametersTable)
throws RowsExceededException, WriteException, IOException {
List<String> demonum = new ArrayList<String>();
List<String> demoname = new ArrayList<String>();
for (Map<String, String> row : parametersTable.getRows()) {
Iterator it = row.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
if (pairs.getKey().equals("demoNumber")) {
demonum.add((String) pairs.getValue());
} else if (pairs.getKey().equals("demoName")) {
demoname.add((String) pairs.getValue());
}
}
}
for(String s:demonum)
{
System.out.println(s.getDemonum);
System.out.println(s.getDemoname);
}
}
We can fetch the multiple row using the Example table parameter here i am passing multiple row from scenario to java class..
I am getting a java.util.ConcurrentModificationException from following code and I can find the reason. I could successfully read data form a csv file and make an arraylist called course list of it. then I need to sort my in to an array list that each of its cell contains an arraylist of identical courses (courses that have similar name).
But when I run it generates ConcurrentModificationException and I do not understand why...
public class CourseLister {
private static final String DATA = "data\\data.csv";
File file;
ArrayList<Course> courseList ;
public CourseLister(String filepath) {
file = new File(filepath);
courseList = new ArrayList<>();
}
public void readFromCsv(){
// in this method a Csv file is written line by line , create a new object of course with some attribute such as name , number, instructor,... and is added to courseList //}
}
public Iterator<Course> getCourseIterator(){
return courseList.iterator();
}
public ArrayList<Course> getCourseList(){
return courseList;
}
public static void main(String [ ] args){
CourseLister courseLister = new CourseLister(DATA);
courseLister.readFromCsv();
CourseFileSorter coursefilesoreter = new CourseFileSorter(courseLister.getCourseIterator());
ArrayList<Course> curseList = courseLister.getCourseList();
for (Course course : curseList) {
System.out.println(course.getSemester());
}
System.out.println(curseList.size());
coursefilesoreter.displayCategorizedList();
}
}
here is my CourefileSorterclass:
public class CourseFileSorter {
Iterator<Course> courseItr ;
public CourseFileSorter(Iterator<Course> courseItr) {
this.courseItr = courseItr;
}
public ArrayList<ArrayList<Course>> getSourtedLists(){
Iterator<Course> dissimilarCourseItr = null;
ArrayList<Course> identicalCourseList = new ArrayList<Course>();
ArrayList<Course> dissimilarCourseList = new ArrayList<Course>();
ArrayList<ArrayList<Course>> categorizedCourseList = new ArrayList<ArrayList<Course>>();
Course firstCourse = null;
Course currentCourse ;
if(courseItr.hasNext()){
while(courseItr.hasNext()){
firstCourse = courseItr.next();
identicalCourseList.add(firstCourse);
while(courseItr.hasNext()){
currentCourse = courseItr.next();
if(currentCourse.getCourseName().equals(firstCourse.getCourseName())){
identicalCourseList.add(currentCourse);
courseItr.remove();
}
else{
dissimilarCourseList.add(currentCourse);
}
}
dissimilarCourseItr = dissimilarCourseList.iterator();
courseItr = dissimilarCourseItr;
categorizedCourseList.add(identicalCourseList);
}
return categorizedCourseList;
}
else{
return null;
}
}
}
It would be much easier to sort them into a different data structure. I see that course has a getCourseName() method, which I assume would return a String object. Try using a Map<String, List<Course>> instead.
The sorting method would look like this:
public Map<String, List<Course>> getSourtedLists(){
Map<String, List<Course>> result = new HashMap<String, List<Course>>();
while(courseItr.hasNext()) {
course next = courseItr.next();
if (!result.containsKey(next.getCourseName())) {
result.put(next.getCourseName(), new ArrayList<Course>());
}
result.get(next.getCourseName()).add(next);
}
Also, you REALLY don't want to call courseItr.remove(); This removes the course object from the underlying Collection, meaning that the way you were planning to do it would empty out the courseList from your CourseLister object.
1 . You get ConcurrentModificationException because:
dissimilarCourseList.add(currentCourse);
courseItr = dissimilarCourseItr;
2 . It's not a good idea to use iterators when you have arraylists.
For my program I want to read a key from a properties file and an associated List of values for the key.
Recently I was trying like that
public static Map<String,List<String>>categoryMap = new Hashtable<String, List<String>>();
Properties prop = new Properties();
try {
prop2.load(new FileInputStream(/displayCategerization.properties));
Set<Object> keys = prop.keySet();
List<String> categoryList = new ArrayList<String>();
for (Object key : keys) {
categoryList.add((String)prop2.get(key));
LogDisplayService.categoryMap.put((String)key,categoryList);
}
System.out.println(categoryList);
System.out.println("Category Map :"+LogDisplayService.categoryMap);
keys = null;
prop = null;
} catch (Throwable e) {
e.printStackTrace();
}
and my properties file is like below -
A=APPLE
A=ALPHABET
A=ANT
B=BAT
B=BALL
B=BUS
I want for key A there should be a list which contain [APPLE, ALPHABET,ANT] and B contain [BAT,BALL,BUS].
So Map should be like this {A=[APPLE, ALPHABET,ANT], B=[BAT,BALL,BUS]} but I get {A=[ANT], B=[BUS]}
I searched on the internet for such a way but found nothing. I wish there should be a way.
Any help?
Try writing the properties as a comma separated list,
then split the value after the properties file is loaded.
For example
a=one,two,three
b=nine,ten,fourteen
You can also use org.apache.commons.configuration and change the value delimiter using the AbstractConfiguration.setListDelimiter(char) method if you're using comma in your values.
The comma separated list option is the easiest but becomes challenging if the values could include commas.
Here is an example of the a.1, a.2, ... approach:
for (String value : getPropertyList(prop, "a"))
{
System.out.println(value);
}
public static List<String> getPropertyList(Properties properties, String name)
{
List<String> result = new ArrayList<String>();
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
if (((String)entry.getKey()).matches("^" + Pattern.quote(name) + "\\.\\d+$"))
{
result.add((String) entry.getValue());
}
}
return result;
}
If this is for some configuration file processing, consider using Apache configuration. https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/index.html?org/apache/commons/configuration/PropertiesConfiguration.html
It has way to multiple values to single key- The format is bit different though
key=value1,value2,valu3 gives three values against same key.
Your logic is flawed... basically, you need to:
get the list for the key
if the list is null, create a new list and put it in the map
add the word to the list
You're not doing step 2.
Here's the code you want:
Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
for (Map.Entry<Object, Object> entry : prop.entrySet())
{
List<String> categoryList = categoryMap.get((String) entry.getKey());
if (categoryList == null)
{
categoryList = new ArrayList<String>();
LogDisplayService.categoryMap.put((String) entry.getKey(), categoryList);
}
categoryList.add((String) entry.getValue());
}
Note also the "correct" way to iterate over the entries of a map/properties - via its entrySet().
Create a wrapper around properties and assume your A value has keys A.1, A.2, etc. Then when asked for A your wrapper will read all the A.* items and build the list. HTH
There's probably a another way or better. But this is how I do this in Spring Boot.
My property file contains the following lines. "," is the delimiter in each line.
mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;
My server config
#Configuration
public class ServerConfig {
#Inject
private Environment env;
#Bean
public MMLProperties mmlProperties() {
MMLProperties properties = new MMLProperties();
properties.setMmmlPots(env.getProperty("mml.pots"));
properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
return properties;
}
}
MMLProperties class.
public class MMLProperties {
private String mmlPots;
private String mmlIsdnGrunntengingar;
private String mmlIsdnStofntengingar;
public MMLProperties() {
super();
}
public void setMmmlPots(String mmlPots) {
this.mmlPots = mmlPots;
}
public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
}
public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
}
// These three public getXXX functions then take care of spliting the properties into List
public List<String> getMmmlCommandForPotsAsList() {
return getPropertieAsList(mmlPots);
}
public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
return getPropertieAsList(mmlIsdnGrunntengingar);
}
public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
return getPropertieAsList(mmlIsdnStofntengingar);
}
private List<String> getPropertieAsList(String propertie) {
return ((propertie != null) || (propertie.length() > 0))
? Arrays.asList(propertie.split("\\s*,\\s*"))
: Collections.emptyList();
}
}
Then in my Runner class I Autowire MMLProperties
#Component
public class Runner implements CommandLineRunner {
#Autowired
MMLProperties mmlProperties;
#Override
public void run(String... arg0) throws Exception {
// Now I can call my getXXX function to retrieve the properties as List
for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
System.out.println(command);
}
}
}
Hope this helps