Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

How can I change one function value in a boolean-valued java Function?

I am having a list of integers, for which every elements gets mapped to a boolean value:

ArrayList<Integer> listOfIntegers = ...;
Function<Integer, Boolean> crazyFunction = new Function<Integer, Boolean>() {
        @Override
        public Boolean apply(Integer integer) {
            return false;
        }
    };;

Now, I'm iterating in a for-loop in which crazyFunction shall be updated each iteration. The update shall just modify one function value, i.e. I want to have something like (in pseudocode):

crazyFunction_tmp(x) := IF x==c THEN true ELSE crazyFunction(x)
crazyFunction := crazyFunction_tmp

for a fixed c.

What would be a good style to do this?

EDIT: Maybe it might be helpful to add some detail. I tried the following:

crazyFunction = new Function<Integer, Boolean>() {
        @Override
        public Boolean apply(Integer integer) {
            if(integer == c)
                return true;
            else return crazyFunction.apply(integer);
        }
    };

but (1) this does not compile since crazyFunction isn't (and shouldn't be) final and (2) this seems to be too complicated. Isn't there an easy way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe what you actually want is to use a Predicate?

Predicate<Integer> crazyFunction = x -> false;
for (Integer thisInteger : listOfIntegers) {
    crazyFunction = crazyFunction.or(Predicate.isEqual(thisInteger));
}

// Is a given integer one of our integers?
boolean isGoodInteger = crazyFunction.apply(42);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...