pavlos163
pavlos163

Reputation: 2890

LinkedHashSet loop from some element onwards (Java).

I am using a LinkedHashSet in my code and at some point I need to iterate and run an algorithm in all the elements of the HashSet from an element onwards.

So if my set contains numbers 1,2,3,4,5. I want to start the loop from the 3 and not the 1. Is this possible?

Thanks.

Upvotes: 1

Views: 807

Answers (3)

fps
fps

Reputation: 34460

If you use a TreeSet instead of a LinkedHashSet, you could use the method tailSet(). If you use it this way: mySet.tailSet(3), it will return a view of your set (that is also a Set), containing only 3, 4, 5.

Upvotes: 1

sprinter
sprinter

Reputation: 27956

There are two possible meanings to 'start the loop from 3'. You could mean you want only items that are equal or greater than 3 in the list. Or you could mean that you want to skip the first 2 items when sorted in a specific order. I would recommend you make your meaning explicitly clear in your code. If you are using Java 8 then streams provide a good mechanism to do this:

myHashSet.stream()
    .sorted(myComparator)
    .skip(2)
    .collect(Collectors.toList());

or

myHashSet.stream()
    .filter(n -> n >= 3)
    .collect(Collectors.toList());

Upvotes: 4

Elliott Frisch
Elliott Frisch

Reputation: 201437

You could copy it into an ArrayList so that you might use subList(int, int); and then you might use a for-each loop like

HashSet<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
for (Integer i : new ArrayList<>(set).subList(2, set.size())) {
    System.out.println(i);
}

Alternatively, you could use the same method to directly get an Iterator like

HashSet<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Iterator<Integer> iter = new ArrayList<>(set).subList(2, set.size())
        .iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

Both output (the requested)

3
4
5

Upvotes: 2

Related Questions