简体   繁体   中英

What is the fastest way to create integer domain?

I have tried to build domain with integer ranges but excluding one point in this range. For example, I should build a range until 4, from always zero. However, I must exclude one point in it say 3. Therefore, my domain should look like array [0,1,2,4]. What is the fastest way to create integer domain?

Create an arraylist of integeres in your domain leaving out one specific element. Something like this:

ArrayList<Integer> domain = new ArrayList<Integer>();    
createDomain(domain, 1, 4, 3);

...
void createDomain(domain, int start, int end, int leaveOutElement) {
    int i;
    for (i = start; i <= end; i++) {
        if (i == leaveOutElement)
            continue;
        domain.add(i);
    }
}

Using Java 8:

final int start = ...;
final int endInclusive = ...;
final int exclude = ...;
int[] domain = IntStream.rangeClosed(start, endInclusive).
        filter(i -> i != exclude).
        toArray();

ie create an IntStream [start, endInclusive] then filter out the value you want to exclude and finally collect it to an array.

As a method:

public int[] createDomain(final int start, final int endInclusive, final int exclude) {
    return IntStream.rangeClosed(start, endInclusive).
            filter(i -> i != exclude).
            toArray();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM