<!ELEMENT foreach (#PCDATA | include | trim | where | set | foreach | choose | if | bind)*> <!ATTLIST foreach collection CDATA #REQUIRED item CDATA #IMPLIED index CDATA #IMPLIED open CDATA #IMPLIED close CDATA #IMPLIED separator CDATA #IMPLIED >
collection 表示需要使用 foreach 的集合,item 表示进行迭代的变量名,index 就是索引值,而 open 跟 close 代表拼接的起始和结束符号,一般就是左右括号,separator 则是每个 item 直接的分隔符
例如写了一个简单的 sql 查询
1 2 3 4 5 6 7 8 9
<selectid="search"parameterType="list"resultMap="StudentMap"> select * from student <where> id in <foreachcollection="list"item="item"open="("close=")"separator=","> #{item} </foreach> </where> </select>
publicbooleancanPartitionKSubsets(int[] nums, int k) { if (k == 1) { returntrue; } intsum=0, n; n = nums.length; for (int num : nums) { sum += num; } if (sum % k != 0) { returnfalse; }
intavg= sum / k; // 排序 Arrays.sort(nums); // 做个前置判断,如果最大值超过分组平均值了就可以返回 false 了 if (nums[n - 1] > avg) { returnfalse; } // 这里取了个巧,先将数组中元素就等于分组平均值的直接排除了 intcalculated=0; for (inti= n - 1; i > 0; i--) { if (nums[i] == avg) { k--; calculated++; } }
int[] bucket = newint[k]; // 初始化 bucket for (inti=0; i < k; i++) { bucket[i] = avg; }