This question already has answers here:
Ways to iterate over a list in Java
(13 answers)
Closed 2 years ago.
So I am using List as object and I want to print values.
public List<Entry> getEntry() {
return entry;
}
public void setEntry(List<Entry> entry) {
this.entry = entry;
}
I am currently printing them one by one like this:
System.out.println(feed.getEntry().get(0).getTitle());
System.out.println(feed.getEntry().get(1).getTitle());
System.out.println(feed.getEntry().get(0));
System.out.println(feed.getEntry().get(1));
How do I need to change that I dont need to print one by one them?
To print all the entires:
feed.getEntry().forEach(System.out::println);
To print all the titles:
feed.getEntry().stream().map(Entry::getTitle).forEach(System.out::println);
To print all entries in the same line separated by spaces:
System.out.println(feed.getEntry().stream().collect(joining(" ")));
List<Entry> entries = Collections.emptyList();
for (Entry entry : entries)
System.out.println(entry);
Pay attetion on not to call entries.get() every time. You have to use Iterator instead.
Related
This question already has answers here:
java - check if a substring is present in an arraylist of strings in java
(3 answers)
How do you check if a list contains an element that matches some predicate?
(2 answers)
How to find an object in an ArrayList by property
(8 answers)
Closed 1 year ago.
How can I check if there is a specific set of letters inside of a value that is inside of an ArrayList?
ArrayList<String> words = new ArrayList<String>();
words.add("Wooden Axe");
words.add("Stone Axe");
if(words.contains("Axe")) {
//something
}
Like how can I check if the values contains the String "Axe"?
If you wanna do a processing afterwards, you can do :
words.stream()
.filter(word -> word.contains("Axe")) // you only keep words with "Axe"
.forEach(word -> System.out.println(word)); // you process them the way you want
You can use the Stream method allMatch();
if(words.stream().allMatch(word -> word.contains("Axe"))) {
//something
}
For a more involved answer, you'd want to go through every item within the array list itself like so:
public static boolean ArrayContainsWord(String match){
for(String word : words){
if(word.Contains(match)){
return true;
}
}
return false;
}
If you'd like to find the exact word that matches with the word you want then you can change the return type of the method "ArrayContainsWord" to return a String instead of a boolean and in the return true line, return the word and return null when you can't find any.
This question already has answers here:
How to count the number of occurrences of an element in a List
(25 answers)
Closed 1 year ago.
For example i have a list:
ArrayList<Observer> arrlist = new ArrayList<Observer>();
The list contains the observer objects
but i want to know the frequency of objects that have the same value for example String name
public class Observer{
private String name;
}
How do i do that?
You basically need to iterate over the observers and count the occurence for each key (could be just a single property or a combination depending on your needs).
Taking your example of the key just being Observer.name you could do the following:
Map<String, List<Observer>> observersByName =
arrlist.stream().collect(Collectors.groupingBy(Observer::getName));
Then iterate over the entry set and call size() on the value lists to get the frequency.
If you directly want to get the frequency, add a counting() collector:
Map<String, Long> nameFrequency = arrlist.stream().collect(
Collectors.groupingBy(Observer::getName,
Collectors.counting()));
If you want to get the frequency without using streams you could use the Map.merge() method:
Map<String, Integer> nameFrequency = new HashMap<>();
for( Observer obs : arrlist ) {
//use the name as the key, associate a value of 1 with each key
//if an entry already existed merge existing and new value by summing them
frequency.merge( obs.getName(), 1, Integer::sum);
}
This question already has an answer here:
Java8 Transform list of object to list of one attribute of object
(1 answer)
Closed 3 years ago.
I need to iterate over Objects and add every elements name to ArrayList.
My class Command contains getName() method.
commands = List< Command >
I've done it without streams.
ArrayList<String> commandList = new ArrayList<String>(); for
(Command currentCommand : commands.getCommands()) {
commandList.add(currentCommand.getName()); }
Here's what I've got now:
commands.getCommands().forEach(command -> { command.getName(); });
I want to do it in one line using streams
Try this
commands.getCommands().stream().map(Command::getName).collect(toList());
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 6 years ago.
I have two rich picklists whose selected item section or destination values must be mutually exclusive. I did this piece of code:-
LinkedHashMap<String,Boolean> includeRatePlans = getCampaign().getDataPackages();
LinkedHashMap<String, Boolean> excludeRatePlans = getCampaign().getSmsPackage();
for (String excludeRatePlan : excludeRatePlans.keySet()){
if(excludeRatePlans.get(excludeRatePlan)){
for (String includeRatePlan : includeRatePlans.keySet()){
if (includeRatePlans.get(includeRatePlan))
if (includeRatePlan.equals(excludeRatePlan)){
getCampaign().getSmsPackage().remove(excludeRatePlan);
}
}
}
}
But I am getting java.util.ConcurrentModificationException
You cannot modify the structure of a Map (i.e. adding or removing entries) while iterating over it with the enhanced for loop (and iterating over the keySet() makes no difference).
You can use an explicit iterator to remove entries :
LinkedHashMap<String,Boolean> includeRatePlans = getCampaign().getDataPackages();
LinkedHashMap<String, Boolean> excludeRatePlans = getCampaign().getSmsPackage();
Iterator<String> iter = excludeRatePlans.keySet().iterator();
while (iter.hasNext()) {
String excludeRatePlan = iter.next();
if(excludeRatePlans.get(excludeRatePlan)) {
for (String includeRatePlan : includeRatePlans.keySet()){
if (includeRatePlans.get(includeRatePlan))
if (includeRatePlan.equals(excludeRatePlan)){
iter.remove();
}
}
}
}
This will work since excludeRatePlans refers to the same Map as getCampaign().getSmsPackage() and removing an element from the KeySet of the Map also removes the corresponding entry from the Map.
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Is there an accepted best practice in Java for deleting a list element while iterating over the list?
(5 answers)
Closed 9 years ago.
How would I write an iterator for this code? I want to remove multiple entries based on input.
public void cancelRegistration(String someName)
{
for (Name n: ArrayList)
{
if(n.Name.equals(someName))
{
ArrayList.remove(n);
}
}
}
You can use Iterator.remove().
Assuming you have a class called Name with a String field called Name and assuming the class cancelRegistration is in has a field called ArrayList of type List<Name>:
public void cancelRegistration(String someName) {
for (Iterator<Name> iterator = ArrayList.iterator(); iterator.hasNext();)
if (iterator.next().Name.equals(someName))
iterator.remove();
}