Java 8 foreach Simple example

Source: Internet
Author: User

1.1 usually traverse a map like this

map<string, integer> items = new hashmap<> (), Items.put ("A", "ten"), Items.put ("B"), Items.put ("C", 30); Items.put ("D", +); Items.put ("E", "a"), Items.put ("F", "a"); for (map.entry<string, integer> Entry:items.entrySet ( ) {    System.out.println ("Item:" + entry.getkey () + "Count:" + entry.getvalue ());}

1.2 In Java8 you can use the foreach + lambda expression to traverse

map<string, integer> items = new hashmap<> (), Items.put ("A", "ten"), Items.put ("B"), Items.put ("C", 30); Items.put ("D", +); Items.put ("E", "a"); Items.put ("F", "a") Items.foreach ((k,v)->system.out.println ("Item:" + k + " Count: "+ V)"); Items.foreach ((k,v)->{    System.out.println ("Item:" + k + "Count:" + V);    if ("E". Equals (k)) {        System.out.println ("Hello E");}    });
2. ForEach and List

2.1 Usually traverse a list like this.

list<string> items = new arraylist<> (), Items.Add ("A"), Items.Add ("B"), Items.Add ("C"), Items.Add ("D"); Items.Add ("E"); for (String item:items) {    System.out.println (item);}

2.2 In Java8 you can use the foreach + lambda expression or the method reference (methods Reference)

list<string> items = new arraylist<> (), Items.Add ("A"), Items.Add ("B"), Items.Add ("C"), Items.Add ("D"); Items.Add ("E");//lambda//output:a,b,c,d,eitems.foreach (Item->system.out.println (item));//Output: Citems.foreach (item->{    if ("C". Equals (item)) {        System.out.println (item);    }}); /method Reference//output:a,b,c,d,eitems.foreach (system.out::p rintln);//stream and Filter//output:bitems.stream ()    . Filter (S->s.contains ("B"))    . ForEach (system.out::p rintln);

Reference Documentation:

    1. Java 8 iterable ForEach JavaDoc
    2. Java 8 ForEach JavaDoc

Java 8 foreach Simple example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.