forEach List

forEach List

Java 8 lambda provide easy and shorten syntax to iterate over the collection. This example show you to loop over the List<NameValuePair>.

Before Java 8

public static void main(String[] args) {
  List<NameValuePair> nvps = new ArrayList<>();
		
  nvps.add(new BasicNameValuePair("cid", "M123-123"));
  nvps.add(new BasicNameValuePair("oid", "TCX-2345"));
  nvps.add(new BasicNameValuePair("cur", "CNY"));
  
  for(NameValuePair nvp : nvps) {
      System.out.println(nvp.getName() + nvp.getValue()) ;
   }
}

Java 8

public static void main(String[] args) {
  List<NameValuePair> nvps = new ArrayList<>();
		
  nvps.add(new BasicNameValuePair("cid", "M123-123"));
  nvps.add(new BasicNameValuePair("oid", "TCX-2345"));
  nvps.add(new BasicNameValuePair("cur", "CNY"));
  nvps.forEach( (bnvp)-> { 
	System.out.println(bnvp.getName() + bnvp.getValue()) ;
  });
		
}

If you’re using eclipse, when you hover the forEach function it will show you hints of the parameters like this:

( Consumer<? super NameValuePair> action )

Consumer is a functional interface that used for assignment target for to support lambda expression, hence, the NameValuePair extends generic type and action means for lambda expression. In this example, NameValuePair is a collection list, bnvp is BasicNameValuePair object refernce. -> pointer mark refer to logic implementation {  }.

 

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.