Is there a shorter way to create sublist from other list?
For example:
I have a Contact obiect, this obiect contain String field of adres
public List<String> getAdreses(long personID) {
List<String> adreses=null;
for(Contact mail : getContacts(personID)){
adreses.add(mail.getMail());
}
return adreses;
}
Try Java Stream:
List<String> adreses = getContacts(personID).stream().map(Contact::getMail).collect(Collectors.toList())
Related
I have a class called Group. Inside Group there is a list the contains objects of type Customer, like so:
Group.java:
private List<Customers> customers;
public List<Customer> getCustomers() {
return customers;
}
Then, like above, the class Customer has list that contains object of type EmailAddress, like so:
Customer.java:
private List<EmailAddress> emailAddresses;
public List<EmailAddress> getEmailAddress() {
return emailAddresses;
}
I want to be able to put this list of email addresses into my own list that I can then manipulate how I want. So in my Main.java I have:
Main.java:
List<Customer> customerList = group.getCustomers(); //group is the object to get <Customer> List
for (int i=0; i<customerList.size(); i++) {
List<EmailAddress> emails = customerList.get(i).getEmailAddresses();
}
Will I then, outside of this for loop, have a List of all the emails of the customers that I can use? Is this the correct way to populate a list that I can then utilize and pull data from outside of this loop? Outside of the loop I want to be able to look at different parts of the list like:
emails.get(3);
or
emails.get(7);
at my own discretion.
You need to initialize the list outside the for cycle
List<EmailAddress> emails = new ArrayList<>();
for (int i=0; i<customerList.size(); i++) {
emails.add(customerList.get(i).getEmailAddresses());
}
List<Customer> customerList = group.getCustomers();
List<EmailAddress> finalEmailAddressList = new ArrayList<>();
for (Customer : customerList) {
if (customer != null) {
finalEmailAddressList.add(customer.getEmailAddresses());
}
}
This should give you a list of all email addresses in the end. You can also use the addAll method to add a collection to a collection (at specific indexes also), in this case, a list.
If access to data is required from an outer scope, the data has to exist in the outer scope. Therefore, you need to declare it in the outer scope of the loop:
List<Customer> customerList = group.getCustomers();
List<EmailAddress> emails = new ArrayList<>(customerList.size());
for (Customer customer : customerList) {
emails.addAll(customer.getEmailAddresses();
}
You can do it with streams:
List<Group> groupList = ...
List<EmailAddress> address = groupList
.stream()
.flatMap(g -> g.getCustomers().stream())
.flatMap(c -> c.getEmailAddresses().stream())
.collect(Collectors.toList());
You can do it in functional style:
List<EmailAddress> emails = costumerList.stream()
.map(Customer::getEmailAddresses)
.flatMap(Collection::stream)
.collect(Collectors.toList());
The most interesting part here is the flatMap() method which does two things:
It maps a List<EmailAddress> to a Stream<EmailAddress> by using method reference of the Collection.stream() method
It flattens the result so that the result is of type Stream<EmailAdress>
Consequently, the result of the collect() method will be of type List<EmailAdress>
In contrast, if the flatMap() line was omitted, the result would be of type List<List<EmailAddress>>.
Similarly, if the map() method was used instead of flatmap(), the result would be of type List<Stream<EmailAddress>>
I am looking for a solution to get a Value from a Property in Android.
I have an ArrayList of Person and I want to get only the property "name" and add it to an ArrayList of Strings.
The code below is in Xamarin and I am looking for the same thing in android studio. Thanks!
foreach (var s in filter.Nodes)
{
nodeName = s.GetType().GetProperty("Name").GetValue(s).ToString();
}
List<String> names = people.stream()
.map(x -> x.name)
.collect(Collectors.toList());
Also I'm unsure why you're still using Java when Kotlin exists...
val names = people.map { it.name }
Create a Model class which will contain properties name like "public String Name". You can use forEach loop to iterate for that Model class and access the property.
public class User{
#SerializedName("Name")
public String name;
}
MainActivity code will be like
for(User user: "your_response"){
list.add(user.name);
}
Try this
ArrayList<String> List = new ArrayList<String>();
for(Person data: filterList){
List.add(data.name);
}
I have 2 array
tickets and filterTickets
I want to return new tickets that does not contain member from filterTickets.
I use this code but filter not working.
List < Ticket > a = new ArrayList <>();
for (String string: ticketsFilter) {
for (Ticket ticket: tickets) {
if (ticket.getTicketId().equals(string))
a.add(ticket);
}
}
From your description , You should have a filterTickets which is a list of strings, then you can use the follow code to check if the filterTickets contains the ticketId:
List<String> ticketsFilter = new ArrayList<>();
...
if(!ticketsFilter.contains(ticket.getTicketId())){
a.add(ticket);
}
Java 8 solution using stream API:
List<Ticket> a = tickets.stream()
.filter(e->!ticketsFilter.contains(e.getTicketId()))
.collect(Collectors.toList());
I have 2 classes, this:
public class TimeCardResponse {
private String login;
List<TimeCardDetail> timeCardDetails;
}
and this:
public TimeCardDetail(String workingDay, Float workingTime) {
this.workingDay = workingDay;
this.workingTime = workingTime;
}
input : a List<TimeCardResponse>
I want to get all workingDay of class TimeCardDetail in a List<String> and using Stream in Java 8.
List<String> workingDays = a.stream().map(TimeCardResponse::getTimeCardDetails)
.filter(x-> Objects::nonNull)
.flatMap(List::stream)
.map(TimeCardDetail::getWorkingDay).collect(toList());
Assuming you have some a getWorkingDay method:
List<String> workDays = timeCardDetails.stream()
.map(TimeCardDetail::getWorkingDay)
.filter(Objects::nonNull) //filter out null values
.collect(Collectors.toList());
Which will return a List<String> of the work days of the time Cards
How can I iterate over list of POJO classes for collecting result of some methods in a standard way to avoid copy past?
I want to have code like this:
//class 'Person' has methods: getNames(), getEmails()
List<Person> people = requester.getPeople(u.getId());
String names = merge(people, Person::getNames);
String emails = merge(people, Person::getEmails);
instead of such copy-pasted logic:
List<Person> people = requester.getPeople(u.getId());
Set<String> namesAll = new HashSet<>();
Set<String> emailsAll = new HashSet<>();
for (Person p : people) {
if(p.getNames()!=null) {
phonesAll.addAll(p.getNames());
}
if(p.getEmails()!=null) {
emailsAll.addAll(p.getEmails());
}
}
String names = Joiner.on(", ").skipNulls().join(namesAll);
String emails = Joiner.on(", ").skipNulls().join(emailsAll);
Thus, is it possible to implement some standard approach for iterating and processing special method of POJO in list that could be reused?
If I understand you correctly, you want something like this :
String names = people.stream().flatMap(p->p.getNames().stream()).distinct().collect(Collectors.joining(", "));
Now, if you want to save typing that line for each property, you can have this merge method as you suggested :
public static String merge (List<Person> people, Function<Person, Collection<String>> mapper)
{
return people.stream().flatMap(p->mapper.apply(p).stream()).distinct().collect(Collectors.joining(", "));
}
This would make your first snippet work.
Now, you can make this method generic :
public static <T> String merge (List<T> list, Function<T, Collection<String>> mapper)
{
return list.stream().flatMap(p->mapper.apply(p).stream()).distinct().collect(Collectors.joining(", "));
}
I think this should work (haven't tested it).