Iterator

使用迭代器遍历hashSet

class Scratch {
    public static void main(String[] args)throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        Set<Integer> userIds = new HashSet<>();
        userIds.add(1);
        userIds.add(2);
        userIds.add(3);
        userIds.add(4);
        userIds.add(5);

        Iterator<Integer> it = userIds.iterator();
        while (it.hasNext()){
            stringBuilder.append(it.next());
            stringBuilder.append(",");
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        System.out.println(stringBuilder.toString());
    }
}

 

posted @ 2022-03-17 15:15  LoveDonkey  阅读(8)  评论(0编辑  收藏  举报