Java8 Stream loop iteration

java 8 stream
convert for loop to stream java 8
java 8 foreach list of objects
java stream foreach
how to iterate list inside list in java 8
java 8 foreach array
iterate string in java 8
for loop with index in java 8

Please anyone help me to do this in Java8 streamAPI,

for(ContactDto contact : contactList){
    for(ContactContactTypeDto contactType : contact.getContactTypes()){
        if(PRIMARY_CONTACT.equals(contactType.getIdContactTypeCode())){
            StringBuilder contactNameSB = new StringBuilder(contact.getFirstName());
            contactNameSB.append(" ");
            if(null!=contact.getMiddleName() && !contact.getMiddleName().isEmpty()){
                contactNameSB.append(contact.getMiddleName());
                contactNameSB.append(" ");
            }
            contactNameSB.append(contact.getLastName());

            contactName = contactNameSB.toString();
            contactEmail = contact.getEmailAddress();
        }
    }
}

I tried but I am reach only upto

contactList.stream()
    .filter(contact -> contact.getContactTypes()
        .stream()
        .anyMatch(contactType -> PRIMARY_CONTACT.equals(contactType.getIdContactTypeCode())));

When code with java 8 streams get convoluted it is beneficial to create some additional types and methods. E.g.

A method to create a full name from it's parts (you don't need StringBuilder the compiler will use one in this case):

String createFullName(ContactDto contact) {
    String contactName = contact.getFirstName() + " ";
    if (null != contact.getMiddleName() && !contact.getMiddleName().isEmpty()) {
        contactName += contact.getMiddleName() + " ";
    }
    return contactName + contact.getLastName();
}

A class to hold the result, basically a pair of name and email (add constructor, getters etc):

class Contact {
    private String name;
    private String email;
}

And now the code becomes much simpler:

Optional<Contact> contact = contactList.stream()
        .filter(c -> c.getContactTypes()
                .stream()
                .map(ContactContactTypeDto::getIdContactTypeCode)
                .anyMatch(PRIMARY_CONTACT::equals))
        .findFirst()
        .map(c -> new Contact(createFullName(c), c.getEmailAddress()));

Extra code after what you have done is findFirst which will returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.

The last map will be applied on the resulting Optional<ContactDTO> if it's not empty to create a Contact or else return an empty Optional<Contact>.

Java 8 forEach examples – Mkyong.com, 1.2 In Java 8, you can loop a Map with forEach + lambda expression. Map<String​, Integer> items = new HashMap<>(); items.put("A", 10);  In this post, we will discuss how to iterate over a Stream with indices in Java 8 and above. We know that elements of Streams in Java 8 and above cannot be directly accessed by using their indices unlike in lists and arrays, but there are few workarounds in Java that makes this feasible which are discussed below in detail:

It may make sense to use a Stream pipeline to obtain the single ContactDto from which you wish to extract details:

ContactDto contact =
    contactList.stream()
               .filter(c -> c.getContactTypes()
                             .stream()
                             .anyMatch(t->PRIMARY_CONTACT.equals(t.getIdContactTypeCode())))
               .findFirst()
               .orElse(null);

Then use that instance to assign the required values to your two variables:

if (contact != null) {
    StringBuilder contactNameSB = new StringBuilder(contact.getFirstName());
    contactNameSB.append(" ");
    if(null!=contact.getMiddleName() && !contact.getMiddleName().isEmpty()) {
        contactNameSB.append(contact.getMiddleName());
        contactNameSB.append(" ");
    }
    contactName = contactNameSB.toString();
    contactEmail = contact.getEmailAddress();
}

Note:

This will assign values based on the first matching ContactDto instance found.

How to Break from Java Stream forEach, Java Streams are often a good replacement for loops. The Java 8 streams library and its forEach method allow us to write that code in a to loops, we are missing the equivalent of the break statement to abort iteration. Having a SIZED stream improves splitting in the case of parallel execution. As Sotirios Delimanolis noted in a comment, you could do something like this: List<MyClass> list = IntStream.range(0, n) .mapToObj(i -> new MyClass()) .collect(toList());

List<ContactDto> contactListWithPrimaryContact = contactList.stream()
                .filter(contact -> contact.getContactTypeDto().parallelStream()
                        .anyMatch(x -> x.getIdContactTypeCode().equals(PRIMARY_CONTACT)))
                .collect(Collectors.toList());

After getting all the contacts with primaryContact type, perform the operations you want further.

getting first contact with type as PRIMARY_CONTACT and assigning value to global variable, seems useless.

because what about the second contact in the list with the contactType as PRIMARY, as per the above solution, we are ignoring it.

How to Iterate Over a Stream With Indices, Java 8 Streams are not collections and elements cannot be accessed using their indices, but there are still a few tricks to make this possible. stringList.stream().forEach() is really just a normal loop under the covers that executes the lambda expression for every iteration. With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):

List<String> listOfPrimaryEmailAddresses = contactList.stream()
                                                      .filter(primaryContactPredicate())
                                                      .map(ContactDto::getEmailAddress)
                                                      .collect(Collectors.toList());


List<String> primaryContactNamesList = contactList.stream()
                                                  .filter(primaryContactPredicate())
                                                  .map(ContactDto::getFullName)
                                                  .collect(Collectors.toList());

private Predicate<ContactDto> primaryContactPredicate() {
        return contact -> contact.getContactTypes().stream().anyMatch(contactType -> PRIMARY_CONTACT.equals(contactType.getIdContactTypeCode()));
}

in ContactDto class add method for getFullName()

public String getFullName() {
        if (null != getMiddleName() && !getMiddleName().isEmpty()) {
            return getFirstName() + " " + getMiddleName() + " " + getLastName();
        }
        return getFirstName() + " " + getLastName();
    }

How do I iterate over a stream in Java using for?, You need an iterable to be able to use a for-each loop, for example a collection or an array: for (String s : strings.stream().filter(s->s.length()  Stream.iterate() Description. The iterate() method takes two arguments: a seed and a function. A seed is the first element of the stream. The second element is generated by applying the function to the first element. The third element is generated by applying the function on the second element.

Program to Iterate over a Stream with Indices in Java 8 , Method 2: Using AtomicInteger. Create an AtomicInteger for index. Get the Stream from the array using Arrays.stream() method. Map each elements of the  The tutorial has illustrated how to iterate over a HashMap in Java 8 by different ways, by using forEach function introduced in Java 8, for loop, Iterator and looping through the key Set of the Map. So, if you’re interested in compatibility with older version of Java such as Java 5, you can use the Iterator.

Java 8 stream foreach get current index, Before java 8, We could iterate over a list by using for loop or iterator. Java 8 – forEach to iterate a Map Streams on Arrays in Java 8 In this article, we would be  Although iterators in Java have taken different forms, using an active iterator was essentially the only viable option prior to Java 8. For a passive iterator (also known as an implicit iterator , internal iterator , or callback iterator ), the iterator itself controls the iteration.

Java performance tutorial – How fast are the Java 8 streams , Java 8 came with a major addition to the JDK collection framework, namely the Again, the for- loop is faster that the sequential stream operation, but the for the ArrayList are dominated by the iteration and boxing overhead  Stream API is one of the main features of Java 8. We can use this feature to loop through a Map as well but as in previous examples, we need to obtain a set of entries first: public void iterateUsingStreamAPI(Map<String, Integer> map) { map.entrySet().stream() //

Comments
  • Your loop doesn't quite make sense, you iterate the contacts but contactEmail and contactName will always be the last ContactDto in the loop because they're overwritten. Are you missing a break?
  • can you explain what should be result. what should perform using contactNameSB. i cant see there any usages of this code.
  • The result of your code is ignored, because you don't do anything with the StringBuilder after appending to it. What do you actually want to happen? For example, should all the matching contacts be collected or just the first?
  • Thanx.. This working fine but I am not suppose to create one more new class
  • In that case you could (ab)use SimpleEntry or one of the Pair implementations in various libraries.
  • Although it could be a train wreck, you could do it in one statement by wrapping the stream result in Optional.ofNullable() then putting the second part in a .map() then do something with it via ifPresent().
  • @Bohemian yes, it can be done (you don't even need Optional.ofNullable(), .findFirst() already returns an Optional). I wouldn't apply map on the Optional, though, since you have to produce two outputs (one assigned to contactName and the other to contactEmail), so you'd have to put the entire second part in ifPresent().