如何在没有迭代器的情况下迭代Set / HashSet?

时间:2012-09-17 08:41:33

标签: java loops set hashset

如何在没有以下内容的情况下迭代Set / HashSet

Iterator iter = set.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

8 个答案:

答案 0 :(得分:440)

您可以使用enhanced for loop

Set<String> set = new HashSet<String>();

//populate set

for (String s : set) {
    System.out.println(s);
}

或者使用Java 8:

set.forEach(System.out::println);

答案 1 :(得分:79)

至少有六种方法可以迭代一组。以下是我所知道的:

方法1

.jpg

方法2

    public static string DownloadSector(string fileurl, int sector)
    {
        string result = string.Empty;
        HttpWebRequest request;
        request = WebRequest.Create(fileurl) as HttpWebRequest;

        //get first 1000 bytes
        request.AddRange(sectorSize*sector, ((sector + 1) * sectorSize) - 1);
        //request.

        Console.WriteLine("Range: " + (sectorSize * sector) + " - " + (((sector + 1) * sectorSize) - 1));

        // the following code is alternative, you may implement the function after your needs
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine("Content length:\t" + response.ContentLength);
            Console.WriteLine("Content type:\t" + response.ContentType);
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                result = sr.ReadToEnd();
            }
        }
        return result;
    }

方法3

// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
  System.out.println(e.nextElement());
}

方法4

for (String movie : movies) {
  System.out.println(movie);
}

方法5

String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
  System.out.println(movieArray[i]);
}

方法6

// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
  System.out.println(movie);
});

这是我用于示例的// Supported in Java 8 and above movies.stream().forEach(movie -> System.out.println(movie));

// Supported in Java 8 and above
movies.stream().forEach(System.out::println);

答案 2 :(得分:22)

将您的论坛转换为数组 也可以帮助您迭代元素:

Object[] array = set.toArray();

for(int i=0; i<array.length; i++)
   Object o = array[i];

答案 3 :(得分:11)

为了演示,请考虑以下集合,它包含不同的Person对象:

Set<Person> people = new HashSet<Person>();
people.add(new Person("Tharindu", 10));
people.add(new Person("Martin", 20));
people.add(new Person("Fowler", 30));
  

人模型类

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //TODO - getters,setters ,overridden toString & compareTo methods

}
  1. for语句有一个用于迭代集合和数组的表单。这种形式有时被称为增强for语句,可用于使循环更紧凑和易于阅读。
  2. for(Person p:people){
      System.out.println(p.getName());
    }
    
    1. Java 8 - java.lang.Iterable.forEach(Consumer)
    2. people.forEach(p -> System.out.println(p.getName()));
      
      default void forEach(Consumer<? super T> action)
      
      Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:
      
      The default implementation behaves as if: 
      
      for (T t : this)
           action.accept(t);
      
      Parameters: action - The action to be performed for each element
      
      Throws: NullPointerException - if the specified action is null
      
      Since: 1.8
      

答案 4 :(得分:9)

以下是关于如何迭代Set及其表演的一些提示:

public class IterateSet {

    public static void main(String[] args) {

        //example Set
        Set<String> set = new HashSet<>();

        set.add("Jack");
        set.add("John");
        set.add("Joe");
        set.add("Josh");

        long startTime = System.nanoTime();
        long endTime = System.nanoTime();

        //using iterator
        System.out.println("Using Iterator");
        startTime = System.nanoTime();
        Iterator<String> setIterator = set.iterator();
        while(setIterator.hasNext()){
            System.out.println(setIterator.next());
        }
        endTime = System.nanoTime();
        long durationIterator = (endTime - startTime);


        //using lambda
        System.out.println("Using Lambda");
        startTime = System.nanoTime();
        set.forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationLambda = (endTime - startTime);


        //using Stream API
        System.out.println("Using Stream API");
        startTime = System.nanoTime();
        set.stream().forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationStreamAPI = (endTime - startTime);


        //using Split Iterator (not recommended)
        System.out.println("Using Split Iterator");
        startTime = System.nanoTime();
        Spliterator<String> splitIterator = set.spliterator();
        splitIterator.forEachRemaining((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationSplitIterator = (endTime - startTime);


        //time calculations
        System.out.println("Iterator Duration:" + durationIterator);
        System.out.println("Lamda Duration:" + durationLambda);
        System.out.println("Stream API:" + durationStreamAPI);
        System.out.println("Split Iterator:"+ durationSplitIterator);
    }
}

代码不言自明。

持续时间的结果是:

Iterator Duration: 495287
Lambda Duration: 50207470
Stream Api:       2427392
Split Iterator:    567294

我们可以看到Lambda花费时间最长,Iterator最快。

答案 5 :(得分:9)

您可以使用功能操作来获得更整洁的代码

Set<String> set = new HashSet<String>();

set.forEach((s) -> {
     System.out.println(s);
});

答案 6 :(得分:1)

枚举():

Enumeration e = new Vector(set).elements();
while (e.hasMoreElements())
    {
        System.out.println(e.nextElement());
    }

另一种方式(java.util.Collections.enumeration()):

for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
    {
        System.out.println(e1.nextElement());
    }

Java 8:

set.forEach(element -> System.out.println(element));

set.stream().forEach((elem) -> {
    System.out.println(elem);
});

答案 7 :(得分:0)

但是,已经有很好的答案。这是我的答案:

1. set.stream().forEach(System.out::println); // It simply uses stream to display set values
2. set.forEach(System.out::println); // It uses Enhanced forEach to display set values

此外,如果此Set为Custom类类型,例如:Customer。

Set<Customer> setCust = new HashSet<>();
    Customer c1 = new Customer(1, "Hena", 20);
    Customer c2 = new Customer(2, "Meena", 24);
    Customer c3 = new Customer(3, "Rahul", 30);

setCust.add(c1);
setCust.add(c2);
setCust.add(c3);
    setCust.forEach((k) -> System.out.println(k.getId()+" "+k.getName()+" "+k.getAge()));

//客户类别:

class Customer{
private int id;
private String name;
private int age;

public Customer(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} // Getter, Setter methods are present.}