Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
975 views
in Technique[技术] by (71.8m points)

jsf - Collection/Array contains method

i was wondering if there's contains method for collections/array in EL 2.2 or i will have to make a custom one ?

REQUIREMENT: i have a string array, and i want to find if it contains a specific string.

CASE: i am looping on list of input checkboxes to render them, and i want to check the current checkbox, if it's value exists in the array of checkboxes.

UPDATE:

  • is such method is available in EL?

  • If such method is not available, then please provide your suggestion for best performance method for a string array contains an element.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a Collection it's easy, just use the Colleciton#contains() method in EL.

<h:panelGroup id="p1" rendered="#{bean.panels.contains('p1')}">...</h:panelGroup>
<h:panelGroup id="p2" rendered="#{bean.panels.contains('p2')}">...</h:panelGroup>
<h:panelGroup id="p3" rendered="#{bean.panels.contains('p3')}">...</h:panelGroup>

For an Object[] (array), you'd need a minimum of EL 3.0 and utilize its new Lambda support.

<h:panelGroup id="p1" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p1').get()}">...</h:panelGroup>
<h:panelGroup id="p2" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p2').get()}">...</h:panelGroup>
<h:panelGroup id="p3" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p3').get()}">...</h:panelGroup>

If you're not on EL 3.0 yet, you'd need to create a custom EL function. For a concrete example, see How to create a custom EL function to invoke a static method? E.g.

public static boolean contains(Object[] array, Object item) {
    return Arrays.asList(array).contains(item);
}

which is registered as

<function>
    <function-name>contains</function-name>
    <function-class>com.example.Functions</function-class>
    <function-signature>boolean contains(java.lang.Object[], java.lang.Object)</function-signature>
</function>

and to be used as

<h:panelGroup ... rendered="#{func:contains(bean.panels, 'u1')}">

This is not available in JSTL. There's a fn:contains(), but that works on String values only.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...