Reputation: 105
I have
Map<String, String> prefixes
and
List<String> annotationProperties
And I am trying to get the string output of
prefix: annotationProperty
for each entry (they were entered in order).
Is there a for loop I could use to concatenate these? I need to return the entries as a List<String>
to use in an XML output.
Thank you!
Upvotes: 0
Views: 87
Reputation: 23634
I assume annotationProperties
is a key for prefix
map. If that is the case then in Java 8 you can do this:
List<String> output = annotationProperties.stream()
.map(prop -> String.format("%s: %s", prefix.get(prop), prop))
.collect(Collectors.toList());
stream
is called so you can use stream functions such as map
and collect
map
is called to transform the strings in annotationProperties
into your desired output
and collect
is called to convert the stream back into a list
If you want to use a for loop then you could also do it like this:
// The end size is known, so initialize the capacity.
List<String> output = new ArrayList<>(annotationProperties.size());
for (String prop : annotationProperties){
output.add(String.format("%s: %s", prefix.get(prop), prop));
}
Can a set a variable equal to
.collect(Collectors.toList());
?
We already have one! In both cases we made a variable output
which is a list of Strings formatted as prefix: property
. If you want to use this list then you can loop over it like this:
for (String mystring : output) {
// do xml creation with mystring
}
or like this:
for (int i = 0; i < output.size(); i++){
String mystring = output.get(i);
// do xml creation with mystring
}
or like this:
output.stream().forEach(mystring -> {
// do xml creation with mystring
});
Upvotes: 1