1

i want to get specific element in a Set in JSF 2 please advise how to do that.

Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498
  • Could you provide an example of what do you want to do? – SJuan76 Aug 08 '12 at 09:29
  • @SJuan76, i want to be able to do something like in the following post on a set http://stackoverflow.com/questions/8637285/how-to-get-specific-element-in-a-list-in-jsf-2 – Mahmoud Saleh Aug 08 '12 at 09:41
  • in that case you should create something like this `public List getSetAsList(){return new ArrayList(mySetVariable);}` – Daniel Aug 08 '12 at 10:25

2 Answers2

9

This problem is not specific to JSF/EL. Already in plain Java you cannot access a specific element in a Set. The Set has no method like get(index) as the List has. You need to convert the Set<T> to a T[] array or a List<T> so that you can access it by an index.

This works in a predictable way for SortedSet or LinkedHashSet only as the elements are then inserted in respectively the sorted order or insertion order. This would not make any sense when it's a HashSet as you cannot reliably predict beforehand at which index the element would end up.

If you're using EL 2.2 (your question history confirms this), then you can just use Set#toArray() to convert it to an array and then use the brace notation [] to access the element by index. The below example prints the second item of the array representation of the #{bean.someSet}.

#{bean.someSet.toArray()[1]}

Again, this makes no sense if it's an unordered set like HashSet.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

Your problem is quite unclear, but JSF2 doesn't really support Set.

Components like ui:repeat or h:datatable always need a sort to display data, so your best choice will be to convert your Set to a List first.

Xavier Portebois
  • 3,354
  • 6
  • 33
  • 53