My JSF Books/Videos My JSF Tutorials OmniFaces/JSF PPTs
JSF 2.3 Tutorial
JSF Caching Tutorial
JSF Navigation Tutorial
JSF Scopes Tutorial
JSF Page Author Beginner's Guide
OmniFaces 2.3 Tutorial Examples
OmniFaces 2.2 Tutorial Examples
JSF Events Tutorial
OmniFaces Callbacks Usages
JSF State Tutorial
JSF and Design Patterns
JSF 2.3 New Features (2.3-m04)
Introduction to OmniFaces
25+ Reasons to use OmniFaces in JSF
OmniFaces Validators
OmniFaces Converters
JSF Design Patterns
Mastering OmniFaces
Reusable and less-verbose JSF code

My JSF Resources ...

Java EE Guardian
Member of JCG Program
Member MVB DZone
Blog curated on ZEEF
OmniFaces is an utility library for JSF, including PrimeFaces, RichFaces, ICEfaces ...

[OmniFaces Utilities] - Find the right JSF OmniFaces 2 utilities methods/functions

Search on blog

Petition by Java EE Guardians

Twitter

miercuri, 28 ianuarie 2015

OmniFaces 2.0 - ReadOnlyValueExpression that can be set when the "real" value is not yet available

Starting with OmniFaces 2.0, we have an out of the box implementation of a read only value expression that can be used when the value is not yet available at construction time, or when the value would be too expensive to create and it's not yet clear if the expression will actually be evaluated. This is an extension of ValueExpression and it is named ReadOnlyValueExpression.

If you need a ValueExpression that respects the above description then you should know that the OmniFaces implementation can be used by instantiating ReadOnlyValueExpression class by using one of the below three constructors. Notice that the value of this ValueExpression is an OmniFaces Callback, which means that when the expression is evaluated, the callback method, invoke(), is called, as being the value of this ValueExpression. Now, the invoke() method can return an object that was "computed" in the meanwhile. Actually, the returned object is the "real" value of the ValueExpression, that wasn't available when this ValueExpression was created. So, the "real" value MUST be calculated somewhere between the creation of the ValueExpression and the evaluation of it, which lead the flow in the invoke() method.
·         create a ReadOnlyValueExpression via a callback which returns a value (the object is the "real" needed value of this ValueExpression)

ReadOnlyValueExpression readOnlyValueExpression = new  
     ReadOnlyValueExpression(type_of_object, new Returning<Object>() {
 @Override
 public Object invoke() {
  return object;
 }
});

·         create a ReadOnlyValueExpression via a callback which takes one argument and returns one value (the object is the "real" needed value of this ValueExpression)

ReadOnlyValueExpression readOnlyValueExpression = new
     ReadOnlyValueExpression(type_of_object, new
           ReturningWithArgument<Object,ELContext>() {
 @Override
 public Object invoke(ELContext elc) {
  return object;
 }
});

Now depends on you where you put this ValueExpression. Per example, based on OmniFaces 2.0 - Write a custom component that receive the FaceletContext for the Facelet in which it is declared, you can place it in the "facelet scope", like this:

...
@Override
public void setFaceletContext(FaceletContext faceletContext) {
 ReadOnlyValueExpression readOnlyValueExpression = new
         ReadOnlyValueExpression(type_of_object, new Returning<Object>() {
  @Override
  public Object invoke() {
   return object;
  }
 });

 faceletContext.getVariableMapper().setVariable(variable_name, readOnlyValueExpression);
}
...

Now, before the #{variable_name...} is evaluated (which will call the invoke() method), you need to ensure that the object is created!

Do not forget that this is a read only ValueExpression, so do not try to set its value. Notice the implementation in the figure below:


You can see a complete use of ReadOnlyValueExpression in the OmniFaces 2.0 component, named ResolveComponent. In that case, OmniFaces puts in "facelet scope" a substitute for an UIComponent that doesn't exist yet. This substitute is an ReadOnlyValueExpression based on the Callback.Returning. Meanwhile, the component is found in the component tree, and when the invoke() method is called (the ValueExpression is evaluated), that UIComponent is returned.

Read further about the OmniFaces 2.1 improvments for this artifact.

JSF 2.2 - Creating a Custom TagHandlerDelegate Skeleton

In order to write and configure a TagHandlerDelegate, you have to accomplish three steps:

·         extract the TagHandlerDelegate and override its methods

public class CustomTagHandlerDelegate extends TagHandlerDelegate {

 private TagHandlerDelegate tagHandlerDelegate;

 public CustomTagHandlerDelegate() {
 }

 public CustomTagHandlerDelegate(TagHandlerDelegate tagHandlerDelegate) {
  this.tagHandlerDelegate = tagHandlerDelegate;
 }

 @Override
 public MetaRuleset createMetaRuleset(Class type) {
  return tagHandlerDelegate.createMetaRuleset(type);
 }

 @Override
 public void apply(FaceletContext ctx, UIComponent comp) throws IOException {
  tagHandlerDelegate.apply(ctx, comp);
 }
}

·         Extend the TagHandlerDelegateFactory and point your TagHandlerDelegate

public class CustomTagHandlerDelegateFactory extends TagHandlerDelegateFactory {
  
    private TagHandlerDelegateFactory tagHandlerDelegateFactory;

    public CustomTagHandlerDelegateFactory() {
    }

    public CustomTagHandlerDelegateFactory(TagHandlerDelegateFactory tagHandlerDelegateFactory) {
        this.tagHandlerDelegateFactory = tagHandlerDelegateFactory;
    }

    @Override
    public TagHandlerDelegate createComponentHandlerDelegate(ComponentHandler owner) {       
        return new CustomTagHandlerDelegate(tagHandlerDelegateFactory.createComponentHandlerDelegate(owner));
    }

    @Override
    public TagHandlerDelegate createValidatorHandlerDelegate(ValidatorHandler owner) {      
        return tagHandlerDelegateFactory.createValidatorHandlerDelegate(owner);
    }

    @Override
    public TagHandlerDelegate createConverterHandlerDelegate(ConverterHandler owner) {     
        return tagHandlerDelegateFactory.createConverterHandlerDelegate(owner);
    }

    @Override
    public TagHandlerDelegate createBehaviorHandlerDelegate(BehaviorHandler owner) {      
        return tagHandlerDelegateFactory.createBehaviorHandlerDelegate(owner);
    }
}

·         configure the your custom TagHandlerDelegateFactory in faces-config.xml

<factory>
 <tag-handler-delegate-factory>
  your_custom_taghandlerdelegatefactory_package.CustomTagHandlerDelegateFactory
 </tag-handler-delegate-factory>
</factory>


Now, most probably, you will go in the apply() method and "play" with the component tree, during its construction.

marți, 27 ianuarie 2015

Use JSF VisitTree API to check a component in the component tree

In this post, you can see how to check a component in the component tree by using the UIComponent.visitTree, declared as follows:

public boolean visitTree(VisitContext context,VisitCallback callback)

First we write a class, named FindByIdVisitCallback, as below:

public class FindByIdVisitCallback implements VisitCallback {

 private final String id;       //can be null
 private final String clientId; //can be null

 public FindByIdVisitCallback(String clientId, String id) {
  this.clientId = clientId;
  this.id = id;
 }

 @Override
 public VisitResult visit(VisitContext context, UIComponent target) {

  if ((id == null) && (clientId == null)) {
       return VisitResult.REJECT;
  }

  if (target.getId().equals(id) || 
         target.getClientId(context.getFacesContext()).equals(clientId)) {
      return VisitResult.COMPLETE;
  }

  return VisitResult.ACCEPT;
}

Now, when we want to use it we follow two simple steps:

·         create an instance of FindByIdVisitCallback class and pass the id/clientId of the component to check
·         call the visitTree() method and capture the boolean result

Note If the result returned by the visitTree() is false, then the checked component doesn't exist, and if it returns true, then the component exist in the indicated tree/sub-tree. This method DOES NOT return an UIComponent instance, this is why I have avoided the term "find component" and prefer "check component". Can be used just for check if a component exist or not in the indicated tree/sub-tree. So, you can check by manually typing the id/clientId, or use something like: myComponent.getId()/myComponent.getClientId(). Nevertheless, you can find the component instance by declaring outside the visitTree(), an UIComponent foundComponent;and, when it is found by the passed id/clientId set it as foundComponent=target.

Examples:
JSF page snippet
...
<h:body> 
 <h:graphicImage id="myImageId" url="http://1.bp.blogspot.com/-
  gtjrtr50mMY/VL0IcD0hbrI/AAAAAAAAA-I/8fmOugRBkvU/s1600/omniutil.png"/>
 <h:form id="myFormId">
  <h:panelGrid id="panelId">             
   Some text
   <h:outputText id="myOutputId" value="..." />
   <h:panelGroup id="myDivId" layout="block">
    <h:inputText id="myInputId" value="..."/>                                     
   </h:panelGroup>
   <h:commandButton id="myButtonId" value="Click me!" />           
  </h:panelGrid>
 </h:form>
</h:body>
...

·         search from UIViewRoot the component with clientId myImageId

FindByIdVisitCallback findByIdVisitCallback = new FindByIdVisitCallback(null, "myImageId");
//or
FindByIdVisitCallback findByIdVisitCallback = new FindByIdVisitCallback("myImageId", null);

boolean result = UIViewRoot.visitTree(VisitContext.createVisitContext(FacesContext), findByIdVisitCallback);

·         search from UIViewRoot the component with id, myInputId / clientId, myFormId:myInputId

FindByIdVisitCallback findByIdVisitCallback = new FindByIdVisitCallback(null, "myInputId");
//or - this will perform faster
FindByIdVisitCallback findByIdVisitCallback = new FindByIdVisitCallback("myFormId:myInputId", null);

boolean result = UIViewRoot.visitTree(VisitContext.createVisitContext(FacesContext), findByIdVisitCallback);

Note  Whenever you can, is better to use clientIds instead of ids, because the search perform faster.
Note   The Visit Tree API has the big advantage that inputs in iterating components (UIData/UIRepeat) will be consulted on a per-iteration basis (otherwise, are consulted only once).

You can see another implementation of Visit Tree API in the OmniFaces Highlight component. There, OmniFaces use this API to traverse a form children, and accomplish some specific tasks for children that are instances of UIInput and are not valid.

JSF Method to Recursively Find Component in Component Tree

Whenever you want to find a component in the component tree, you can use:
But, sometimes you need to get down to the most time consuming search. Use, this approach as the last solution (pass to it the component tree/sub-tree in which to search and the clientId of the component to find - if the searched component cannot be found, this method returns null):

import static org.omnifaces.util.Utils.isEmpty;
...
private static <C extends UIComponent> C findComponentRecursively(UIComponent component, String clientId) {

 if (isEmpty(clientId)) {
     return null;
 }

 for (UIComponent child : component.getChildren()) {
      UIComponent result;

      try {
          result = child.findComponent(clientId);
      } catch (IllegalArgumentException e) {
        continue;
      }

      if (result == null) {
          result = findComponentRecursively(child, clientId);
     }

     if (result != null) {
         return (C) result;
     }
 }
 return null;

}

Examples:
JSF page snippet
...
<h:body> 
 <h:graphicImage id="myImageId" url="http://1.bp.blogspot.com/-
  gtjrtr50mMY/VL0IcD0hbrI/AAAAAAAAA-I/8fmOugRBkvU/s1600/omniutil.png"/>
 <h:form id="myFormId">
  <h:panelGrid id="panelId">             
   Some text
   <h:outputText id="myOutputId" value="..." />
   <h:panelGroup id="myDivId" layout="block">
    <h:inputText id="myInputId" value="..."/>                                     
   </h:panelGroup>
   <h:commandButton id="myButtonId" value="Click me!" />           
  </h:panelGrid>
 </h:form>
</h:body>
...

·         search from UIViewRoot the component with clientId myImageId
UIComponent found = findComponentRecursively(UIViewRoot, "myImageId");

·         search from UIViewRoot the component with id, myInputId / clientId, myFormId:myInputId

UIComponent found = findComponentRecursively(UIViewRoot, "myInputId");

//this will perform faster
UIComponent found = findComponentRecursively(UIViewRoot, "myFormId:myInputId");


Note  Whenever you can, is better to use clientIds instead of ids, because the search perform faster.

[OmniFaces utilities (2.0)] Add the given data argument/arguments/mapping of data arguments to the current ajax response


[OmniFaces utilities] The data() methods add the given data argument/arguments/mapping of data arguments to the current ajax response.

Method (add argument):
Method (add arguments):
Method (add mapping of data arguments):
Usage of all three:

JSF Page: 
...
<h:head>
 <title></title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script type="text/javascript">
  function showData() {
   var data = OmniFaces.Ajax.data;
   var $showData = $("#showData");

   $.each(data, function (key, value) {
     $("&lt;li&gt;").text(key + "=" + JSON.stringify(value)).appendTo($showData);
   });
  }
 </script>
</h:head>
<h:body>
 <h:form>
  <ul id="showData"></ul>
  <h:commandButton value="Show Players Data" onclick="$('#showData').empty()"
                   action="#{playersBean.showPlayers()}">
   <f:ajax />
  </h:commandButton>
 </h:form>
</h:body>
...

JSF Bean:
import org.omnifaces.util.Ajax;
...
@Named
@ViewScoped
public class PlayersBean implements Serializable {

 private List<Players> players = new ArrayList<>();
 final SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

 public PlayersBean() {
  try {
      players.add(new Players(2, "NOVAK DJOKOVIC", (byte) 26, "Belgrade, Serbia",
      "Monte Carlo, Monaco", (short) 188, (byte) 80, "Boris Becker, Marian Vajda",
      sdf.parse("22.05.1987")));
      players.add(new Players(1, "RAFAEL NADAL", (byte) 27, "Manacor, Mallorca,
      Spain", "Manacor, Mallorca, Spain", (short) 185, (byte) 85, "Toni Nadal",
      sdf.parse("03.06.1986")));
      players.add(new Players(7, "TOMAS BERDYCH", (byte) 28, "Valasske Mezirici,
      Czech", "Monte Carlo, Monaco", (short) 196, (byte) 91, "Tomas Krupa",
      sdf.parse("17.09.1985")));
  } catch (ParseException ex) {
    Logger.getLogger(PlayersBean.class.getName()).log(Level.SEVERE, null, ex);
  }
 }

 public void showPlayers() {
  Ajax.data("First Player: ", players.get(0).getPlayer());
  Ajax.data("First Player:", players.get(0).getPlayer(),
            "Last Player", players.get(players.size() - 1).getPlayer());
  Map<String, Object> data = new HashMap<>();
  data.put("name", players.get(0).getPlayer());
  data.put("age", players.get(0).getAge());
  data.put("born", players.get(0).getBorn());
  data.put("heights", new Short[]{players.get(0).getHeight(),
    players.get(1).getHeight(), players.get(2).getHeight()});
  data.put("list", players);
  Ajax.data(data);
  Ajax.oncomplete("showData()");
  }

}

Output:

luni, 26 ianuarie 2015

JSF 2.2 and Expression Language 3.0 (EL 3.0) - over 50 examples

assigment operator (=), concatenation operator (+=), semicolon operator (;), lambda expressions

Collections used in these examples:

EL 3.0 Expressions Examples


A. New Operators: '+' ,'=', ';'


  1. #‌{x = 3}evaluates to: 3
  2. #‌{y = x + 5}evaluates to: 8
  3. #‌{z = y = x + 4}evaluates to: 7
  4. #‌{0 += 0 +=0 += 1 += 1 += 0 += 0 += 0}evaluates to: 00011000
  5. #‌{x += y}evaluates to: 37
  6. #‌{"Rafael " += "Nadal " += "Parera"}evaluates to: Rafael Nadal Parera
  7. #‌{x = 5; y = 3; z = x + y}evaluates to: 8

B. Lambda Expression Invoked Immediately


  1. #‌{(x->x+1)(3)}evaluates to: 4
  2. #‌{((x,y)->x+y)(2,7)}evaluates to: 9
  3. #‌{((x,y,z)->x-y*z)(1,7,3)}evaluates to: -20
  4. #‌{((x,y)->x/y)(1,5)}evaluates to: 0.2

C. Assigned Lambda Expression - Referenced and Invoked Indirectly


  1. #‌{q = x->x+1; q(3)}evaluates to: 4
  2. #‌{q = (x,y)->x+y; q(2,7)}evaluates to: 9
  3. #‌{q = ((x,y,z)->x-y*z); q(1,7,3)}evaluates to: -20
  4. #‌{q = ((x,y)->x/y); q(1,5)}evaluates to: 0.2
  5. Factorial n recursive function:
    #‌{fact = n -> n==0? 1: n*fact(n-1); fact(5)}evaluates to: 120
  6. Compute n mod m without using %:
    #‌{modulus = (n,m) -> m eq 0 ? 0 : (n lt m ? n: (modulus(n-m, m))); modulus(13,5)}evaluates to: 3
  7. Greatest common divisor of 2 numbers (uses the above modulus function):
    #‌{gcd = (n,m) -> modulus(n,m) == 0 ? m: (gcd(m, modulus(n,m))); gcd(10, 15)}evaluates to: 5

The methods listed below are called in sections D and E (this code is in LambdaBean):

public Object firstLambdaAction(LambdaExpression lambdaExpression) {

 //useful in case of a custom ELContext
 FacesContext facesContext = FacesContext.getCurrentInstance();
 ELContext elContext = facesContext.getELContext();
 return lambdaExpression.invoke(elContext, 8, 3);

 //or simply, default ELContext:
 //return lambdaExpression.invoke(8, 3);
}

public Object secondLambdaAction(LambdaExpression lambdaExpression) {

 FacesContext facesContext = FacesContext.getCurrentInstance();
 ELContext elContext = facesContext.getELContext();

 Map<String, Object> args = new HashMap<>();
 args.put("n", 17);
 args.put("m", 4);
 elContext.enterLambdaScope(args);
 Object result = lambdaExpression.invoke(elContext.isLambdaArgument("n") ?
  elContext.getLambdaArgument("n") : 0, elContext.isLambdaArgument("m") ?
  elContext.getLambdaArgument("m") : 0);
 elContext.exitLambdaScope();

 return result;
}

public Object thirdLambdaAction(LambdaExpression lambdaExpression) {
 return lambdaExpression.invoke(10);
}

D. Lambda Expression Passed as an Argument to a Method


  1. Call bean method named firstLambdaAction with lambda expression as argument:
    #‌{lambdaBean.firstLambdaAction(modulus = (n,m) -> m eq 0 ? 0 : (n lt m ? n: (modulus(n-m, m))))}evaluates to: 2
  2. Call bean method named secondLambdaAction with lambda expression as argument:
    #‌{lambdaBean.secondLambdaAction(modulus = (n,m) -> m eq 0 ? 0 : (n lt m ? n: (modulus(n-m, m))))}evaluates to: 1

E. Nested Lambda Expressions


  1. #‌{(x->x-((x,y)->(x+y))(4,3))(10)}evaluates to: 3
  2. Call thirdLambdaAction with nested lambda expression as argument:
    #‌{lambdaBean.thirdLambdaAction((x->x-((x,y)->(x+y))(4,3)))}evaluates to: 3

F. Lambda Streams - using Collections


  1. Sort ascending/descending a list:
    #‌{[21,23,12,444,9,1,45].stream().sorted((i,j)->i-j).toList()}ascending to [1, 9, 12, 21, 23, 45, 444]
    #‌{[21,23,12,444,9,1,45].stream().sorted((i,j)->j-i).toList()}descending to [444, 45, 23, 21, 12, 9, 1]
  2. Create an instance of java.lang.util.Set<Object> without displaying it:
    #‌{nr_set = {1,2,3,4,5,6,7,8,9,10};''}evaluates to: it was created but not displayed!
    Create an instance of java.lang.util.List<Object> without displaying it:
    #‌{nr_list = [1,2,3,4,5,6,7,8,9,10];''}evaluates to: it was created but not displayed!
    Create an instance of java.lang.util.Map<Object> without displaying it:
    #‌{nr_map = {"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"ten":10};''}evaluates to: it was created but not displayed!
  3. Display even values from nr_set Set:
    #‌{nr_set.stream().filter(x-> x%2 == 0).toList()}evaluates to: [2, 4, 6, 8, 10]
  4. Display values divisible by 5 from nr_list List
    #‌{nr_list.stream().filter(x-> x%5 == 0).toList()}evaluates to: [5, 10]
  5. Display key/value pairs from nr_map Map using ui:repeat and += operator (NO lambda expression):
    <ui:repeat value="#‌{nr_map.entrySet().toArray()}" var="t"> #‌{t.key += "-" += t.value} </ui:repeat>evaluates to: nine-9 | six-6 | four-4 | one-1 | seven-7 | ten-10 | two-2 | three-3 | five-5 | eight-8 |
  6. Display the nr_map values using values() method:
    #‌{nr_map.values().stream().toList()}evaluates to: [9, 6, 4, 1, 7, 10, 2, 3, 5, 8]
  7. Display the nr_map keys using keySet() method:
    #‌{nr_map.keySet().stream().toList()}evaluates to: [nine, six, four, one, seven, ten, two, three, five, eight]
  8. Display the nr_map keys/values using keySet() method:
    #‌{nr_map.keySet().stream().map((x)->[x,nr_map.get(x)]).toList()}evaluates to: [[nine, 9], [six, 6], [four, 4], [one, 1], [seven, 7], [ten, 10], [two, 2], [three, 3], [five, 5], [eight, 8]]
  9. Display the nr_map keys/values using entrySet() method:
    #‌{nr_map.entrySet().stream().map((x)->[x.key, x.value]).toList()}evaluates to: [[nine, 9], [six, 6], [four, 4], [one, 1], [seven, 7], [ten, 10], [two, 2], [three, 3], [five, 5], [eight, 8]]
  10. Filter even values from a java.lang.util.List<Object> and convert the result into an array:
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t += " | "} </ui:repeat>
    #‌{[132,22,113,4454,345].stream().filter(x-> x%2 == 0).toArray()}evaluates to: 132 | 22 | 4454 |
  11. Find first item in primes java.util.List:
    #‌{lambdaBean.primes.stream().findFirst().get()}evaluates to: 11
  12. Count number of items in primes java.util.List:
    #‌{lambdaBean.primes.stream().count()}evaluates to: 10
  13. Sum primes items in primes java.util.List:
    #‌{lambdaBean.primes.stream().sum()}evaluates to: 129
  14. Compute minimum item value in primes java.util.List:
    #‌{lambdaBean.primes.stream().min().get()}evaluates to: 2
  15. Compute average value in primes java.util.List:
    #‌{lambdaBean.primes.stream().average().get()}evaluates to: 12.9
  16. Compute maximum item value in primes java.util.List:
    #‌{lambdaBean.primes.stream().max().get()}evaluates to: 29
  17. Extract a sublist of primes java.util.List, between start, 2 and end, 6:
    #‌{(lambdaBean.primes.stream().substream(2,6)).toList()}evaluates to: [5, 19, 2, 13]
  18. Check that none of the languages (java.util.List) items is equal to Cobol text:
    #‌{(lambdaBean.languages.stream().noneMatch(x->x.equals('Cobol')))}evaluates to: true
  19. Check if all orders (java.util.List) items are equal to order#23200:
    #‌{(lambdaBean.orders.stream().allMatch(x->x.equals('order#23200')))}evaluates to: true
  20. Check if any item of languages (java.util.List) is equal to Scala text:
    #‌{(lambdaBean.languages.stream().anyMatch(x->x.equals('Scala')))}evaluates to: true
  21. Check if there are any costs less then 1000 in costBeforeVAT (java.util.List):
    #‌{(lambdaBean.costBeforeVAT.stream().anyMatch(x->x lt 1000))}evaluates to: true
  22. Sort and iterate the languages (java.util.List):
    #‌{(lambdaBean.languages.stream().sorted()).toList()}evaluates to: [Accent, Basic, C++, Delphi, Fortran, Haskell, Inform, Java, Lisp, Onyx, Scala]
  23. Display the first three biggest costs in costBeforeVAT (java.util.List):
    #‌{(lambdaBean.costBeforeVAT.stream().sorted((x,y)->y-x).limit(3)).toList()}evaluates to: [15222, 10000, 2200]
  24. Iterate distinct items from names (java.util.List):
    #‌{(lambdaBean.names.stream().distinct()).toList()}evaluates to: [Mark, John, Nelly, Kelly, Raul, Molly, Sully]
  25. Iterate distinct items in uppercase from names (java.util.List):
    #‌{(lambdaBean.names.stream().map((name)->name.toUpperCase()).distinct()).toList()}evaluates to: [MARK, JOHN, NELLY, KELLY, RAUL, MOLLY, SULLY]
  26. Display all names (allows duplicates) that ends with y in names (java.util.List):
    #‌{(lambdaBean.names.stream().filter((name)->name.endsWith('y'))).toList()}evaluates to: [Nelly, Kelly, Kelly, Molly, Sully]
  27. Display all names (allows duplicates) that starts with R in names (java.util.List):
    #‌{(lambdaBean.names.stream().filter((name)->name.startsWith('R'))).toList()}evaluates to: [Raul]
  28. Applying 24% VAT on each cost in costBeforeVAT (java.util.List):
    #‌{(lambdaBean.costBeforeVAT.stream().map((cost) -> cost + .24*cost)).toList()}evaluates to: [42.16, 2728.0, 1674.0, 533.2, 70.68, 12400.0, 28.52, 18875.28, 1.24]
  29. Sort languages (java.util.List) in the order of word length; and then for words of the same length, in alphabetical order:
    #‌{lambdaBean.languages.stream().sorted((x,y)->(x.length()==y.length()? x.compareTo(y) : x.length() - y.length())).toList()}evaluates to: [C++, Java, Lisp, Onyx, Basic, Scala, Accent, Delphi, Inform, Fortran, Haskell]
  30. Applying 24% VAT and compute total for costs in costBeforeVAT (java.util.List):
    #‌{(lambdaBean.costBeforeVAT.stream().map((cost) -> cost + .24*cost)).reduce((sum, cost) -> sum + cost).get()}evaluates to: 36353.079999999994
  31. Applying 24% VAT and compute total for costs bigger than 1000 in costBeforeVAT (java.util.List):
    #‌{(lambdaBean.costBeforeVAT.stream().filter((cost)-> cost gt 1000).map((cost) -> cost + .24*cost)).reduce((sum, cost) -> sum + cost).get()}evaluates to: 35677.28
  32. List all string with more than 3 characters toothless (java.util.List):
    #‌{(lambdaBean.toothless.stream().filter((tooth) -> tooth.length()> 3)).toList()}evaluates to: [abcde, qwert, klmno]
  33. Count number of appearances of age 28 in dataArrayList (java.util.ArrayList):
    #‌{playersBean.dataArrayList.stream().filter((x)->x.age eq 28).toList().size()}evaluates to: 3
  34. Sort ascending and display all players in dataArrayList (java.util.ArrayList) by name:
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t.player += " | "} </ui:repeat>
    #‌{(playersBean.dataArrayList.stream().sorted((x,y)->x.player.compareTo(y.player))).toList()}evaluates to: ANDY MURRAY | DAVID FERRER | JO-WILFRIED TSONGA | JUAN MARTIN DEL POTRO | NOVAK DJOKOVIC | RAFAEL NADAL | RICHARD GASQUET | ROGER FEDERER | STANISLAS WAWRINKA | TOMAS BERDYCH |
  35. Sort ascending and display all players in dataArrayList (java.util.ArrayList) by name using a function:
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t.player += " | "} </ui:repeat>
    #‌{comparing = map->(x,y)->map(x).compareTo(map(y));''}
    #‌{(playersBean.dataArrayList.stream().sorted(comparing((t)->t.player))).toList()}
    evaluates to: ANDY MURRAY | DAVID FERRER | JO-WILFRIED TSONGA | JUAN MARTIN DEL POTRO | NOVAK DJOKOVIC | RAFAEL NADAL | RICHARD GASQUET | ROGER FEDERER | STANISLAS WAWRINKA | TOMAS BERDYCH |
  36. Sort descending and display all players in dataArrayList (java.util.ArrayList) by name:
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t.player += " | "} </ui:repeat>
    #‌{(playersBean.dataArrayList.stream().sorted((x,y)->y.player.compareTo(x.player))).toList()}evaluates to: TOMAS BERDYCH | STANISLAS WAWRINKA | ROGER FEDERER | RICHARD GASQUET | RAFAEL NADAL | NOVAK DJOKOVIC | JUAN MARTIN DEL POTRO | JO-WILFRIED TSONGA | DAVID FERRER | ANDY MURRAY |
  37. List all players older than 30 in dataArrayList (java.util.ArrayList):
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t.player += " | "} </ui:repeat>
    #‌{(playersBean.dataArrayList.stream().filter((p)->p.age ge 30)).toList()}evaluates to: ROGER FEDERER | DAVID FERRER |
  38. Extract, by name, all players in dataArrayList (java.util.ArrayList) using map :
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t += " | "} </ui:repeat>
    #‌{playersBean.dataArrayList.stream().map((x)->x.player).toList()}evaluates to: NOVAK DJOKOVIC | RAFAEL NADAL | TOMAS BERDYCH | STANISLAS WAWRINKA | ANDY MURRAY | JUAN MARTIN DEL POTRO | JO-WILFRIED TSONGA | ROGER FEDERER | RICHARD GASQUET | DAVID FERRER |
  39. Extract players by name, height and weight using map - only players older than 27 in dataArrayList (java.util.ArrayList):
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t[0] += ' is ' += (t[1]/100) += ' m height and weights ' += t[2] += ' kg'} </ui:repeat>
    #‌{playersBean.dataArrayList.stream().filter((p)->p.age gt 27).map((p)->[p.player, p.height, p.weight]).toList()}evaluates to:
    TOMAS BERDYCH is 1.96 m height and weights 91 kg
    STANISLAS WAWRINKA is 1.83 m height and weights 81 kg
    JO-WILFRIED TSONGA is 1.88 m height and weights 91 kg
    ROGER FEDERER is 1.85 m height and weights 85 kg
    DAVID FERRER is 1.75 m height and weights 73 kg
  40. List all players in dataArrayList (java.util.ArrayList) with age between 27 and 29:
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t += " | "} </ui:repeat>
    #‌{(playersBean.dataArrayList.stream().filter((p)->p.age ge 27).filter((p)->p.age le 29)).toList()}evaluates to: RAFAEL NADAL | TOMAS BERDYCH | STANISLAS WAWRINKA | JO-WILFRIED TSONGA | RICHARD GASQUET |
  41. List all players in dataArrayList (java.util.ArrayList) born after 1985:
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t.player} born in #‌{t.born.year + 1900} </ui:repeat>
    #‌{(playersBean.dataArrayList.stream().filter((p)->(p.born.year+1900) gt 1985)).toList()}evaluates to:
    NOVAK DJOKOVIC born in 1987
    RAFAEL NADAL born in 1986
    ANDY MURRAY born in 1987
    JUAN MARTIN DEL POTRO born in 1988
    RICHARD GASQUET born in 1986
  42. Display the youngest and the oldest player in dataArrayList (java.util.ArrayList):
    Youngest:#‌{playersBean.dataArrayList.stream().max((x,y)->y.age-x.age).get().player}Oldest:#‌{playersBean.dataArrayList.stream().max((x,y)->x.age-y.age).get().player}evaluates to:
    Youngest: JUAN MARTIN DEL POTRO
    Oldest: ROGER FEDERER
  43. Display the longest player name in dataArrayList (java.util.ArrayList):
    #‌{playersBean.dataArrayList.stream().max((x,y)->x.player.length()-(y.player.length())).get().player}evaluates to: JUAN MARTIN DEL POTRO
  44. Display players names from dataHashMap (java.util.Map) using values() method:
    #‌{playersBean.dataHashMap.values().stream().map((x)->x.player).toList()}evaluates to: [RAFAEL NADAL, NOVAK DJOKOVIC, DAVID FERRER, ANDY MURRAY, JUAN MARTIN DEL POTRO, ROGER FEDERER, TOMAS BERDYCH, STANISLAS WAWRINKA, RICHARD GASQUET, JO-WILFRIED TSONGA]
  45. Display players keys from dataHashMap (java.util.Map) using keySet() method:
    #‌{playersBean.dataHashMap.keySet().stream().toList()}evaluates to: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  46. Display players heights from dataHashMap (java.util.Map) using keySet() method:
    #‌{playersBean.dataHashMap.keySet().stream().map((x)->[x,playersBean.dataHashMap.get(x).height]).toList()}evaluates to: [[1, 185], [2, 188], [3, 175], [4, 190], [5, 198], [6, 185], [7, 196], [8, 183], [9, 185], [10, 188]]
  47. Display players keys/names from dataHashMap (java.util.Map) using entrySet() method:
    #‌{playersBean.dataHashMap.entrySet().stream().map((x)->[x.key, x.value.player]).toList()}evaluates to: [[1, RAFAEL NADAL], [2, NOVAK DJOKOVIC], [3, DAVID FERRER], [4, ANDY MURRAY], [5, JUAN MARTIN DEL POTRO], [6, ROGER FEDERER], [7, TOMAS BERDYCH], [8, STANISLAS WAWRINKA], [9, RICHARD GASQUET], [10, JO-WILFRIED TSONGA]]
  48. Display players names sorted by key from dataHashMap (java.util.Map) using entrySet() method:
    #‌{playersBean.dataHashMap.entrySet().stream().sorted((x,y)->x.key-y.key).map((x)->[x.key,x.value.player]).toList()}evaluates to: [[1, RAFAEL NADAL], [2, NOVAK DJOKOVIC], [3, DAVID FERRER], [4, ANDY MURRAY], [5, JUAN MARTIN DEL POTRO], [6, ROGER FEDERER], [7, TOMAS BERDYCH], [8, STANISLAS WAWRINKA], [9, RICHARD GASQUET], [10, JO-WILFRIED TSONGA]]
  49. Display players names sorted by names from dataHashMap (java.util.Map) using entrySet() method:
    #‌{playersBean.dataHashMap.entrySet().stream().sorted((x,y)->x.value.player.compareTo(y.value.player)).map((x)->[x.key,x.value.player]).toList()}evaluates to: [[4, ANDY MURRAY], [3, DAVID FERRER], [10, JO-WILFRIED TSONGA], [5, JUAN MARTIN DEL POTRO], [2, NOVAK DJOKOVIC], [1, RAFAEL NADAL], [9, RICHARD GASQUET], [6, ROGER FEDERER], [8, STANISLAS WAWRINKA], [7, TOMAS BERDYCH]]
  50. Display players from dataHashMap (java.util.Map), sorted by birthday, using entrySet() method:
    #‌{playersBean.dataHashMap.entrySet().stream().sorted((x,y)->x.value.born.compareTo(y.value.born)).map((x)->[x.key,x.value.player,x.value.born.year+1900]).toList()}evaluates to: [[6, ROGER FEDERER, 1981], [3, DAVID FERRER, 1982], [8, STANISLAS WAWRINKA, 1985], [10, JO-WILFRIED TSONGA, 1985], [7, TOMAS BERDYCH, 1985], [1, RAFAEL NADAL, 1986], [9, RICHARD GASQUET, 1986], [4, ANDY MURRAY, 1987], [2, NOVAK DJOKOVIC, 1987], [5, JUAN MARTIN DEL POTRO, 1988]]
  51. Compute the youngest player from dataHashMap (java.util.Map) using values() method:
    #‌{(playersBean.dataHashMap.values().stream().max((x,y)->y.age-x.age).get()).player}evaluates to: JUAN MARTIN DEL POTRO
  52. Compute the oldest player from dataHashMap (java.util.Map) using values() method:
    #‌{(playersBean.dataHashMap.values().stream().max((x,y)->x.age-y.age).get()).player}evaluates to: ROGER FEDERER
  53. Display the players from dataHashMap (java.util.Map) using entrySet() method - only players with odd keys and starting with R:
    for display use: <ui:repeat value="below_expression" var="t"> #‌{t.key += "-" += t.value.player} </ui:repeat>
    #‌{((playersBean.dataHashMap.entrySet().stream().filter((x)->x.key%2 ne 0)).filter((x)->x.value.player.startsWith('R'))).toList()}evaluates to:
    1-RAFAEL NADAL
    9-RICHARD GASQUET

JSF BOOKS COLLECTION

Postări populare

OmniFaces/JSF Fans

Follow by Email

Visitors Starting 4 September 2015

Locations of Site Visitors