Reputation: 331
So I'm wondering how would I be able to grab the currents values from an ArrayList and add-on values to it.
private List<String> friends;
public Profile(List<String> friends){
this.friends = friends
}
public List<String> getFriends() {
return friends;
}
public void addFriend(List<String> friends) {
this.friends = getFriends() + friends;
}
Obviously, the method "addFriend" won't working because an operator cannot be applied to an ArrayList. It supposes to be an example of how it should exactly work. Grabbing getFriends() method and applying another list to it. So is there a way that I can accomplish this task? Grabbing a getter ArrayList and adding values ONTO it.
Note: Already assumed that the data is stored somewhere in an hashmap with a key and a value as an List
Upvotes: 0
Views: 86
Reputation: 331
All of these answers will work, I might as well add a my own solution as well.
public void addFriend(List<String> friends) {
this.friends.addAll(friends.stream().collect(Collectors.toList()));
}
Upvotes: 0
Reputation: 3559
You could create two different methods:
This way you add a list of friends to the current list
public void addFriend(List<String> friends) {
this.friends.addAll(friends);
}
This way you only add one friend
public void addFriend(String friend) {
this.friends.add(friend);
}
With this approach you will have two different behaviours for adding friends.
Upvotes: 0
Reputation: 12953
You can use ArrayList.addAll(Collection c)
method:
public void addFriend(List<String> friends) {
this.friends.addAll(friends);
}
Upvotes: 0
Reputation: 17142
You can use this:
public void addFriend(List<String> friends) {
this.friends.addAll(friends);
}
Upvotes: 1
Reputation: 4998
Why don't you just iterate and add to the friends
field? It's already a list...
public void addFriend(List<String> friends) {
for (String friend : friends) {
this.friends.add(friend);
}
}
Upvotes: 1