Ullas Hunka
Ullas Hunka

Reputation: 2211

Convert an arraylist of integer to arraylist of boolean

I have an arraylist containing integers want to convert this into arraylist of boolean.

The code which I tried is containing a loop is there any other faster way to do the same.

The sample used.

private ArrayList<Boolean> changeThis(ArrayList<Integer> arr){
    ArrayList<Boolean> a = new ArrayList<>();
    for(int i=0 ; i < arr.size() ; i++){
        a.add(arr.get(i) == 1);
    }
    return a;
}

and the input for the above method is as follows:

changeThis(arr);//arr has [1,0,1,0,0,0]

Upvotes: 0

Views: 869

Answers (2)

GhostCat
GhostCat

Reputation: 140525

Edit: given the update that the actual is value[index] == 1, the answer is of course:

return incomingList.stream().map( (number) -> number == 1 ).collect(Collectors.toList());

This could then be changed to use parallelStream() to get to results quicker. The parallel solution is of course only decreasing overall runtime when talking about a really large number of numbers in that list! For small data sets, using stream() or parallelStream() will most likely increase the time required to compute the result list.

The other thing to look at: where are the numbers coming actually from? Maybe there is a chance to use an IntStream instead of List<Integer>.


For completeness, the initial answer, based on the assumption that we need to compare against the index, instead of 1:

Actually, this is one of the occasions where there is no way to improve much (except the wording, as the variable names are really meaningless).

The thing is: in order to compute the condition, you need to compare the list slot against its index.

Thus you need that counting for loop (somehow). Any stream() based solution would require extra work to get to that information; same when using foreach().

So, long story short: stay with the "old school" iterative way here!

Upvotes: 3

Morteza Jalambadani
Morteza Jalambadani

Reputation: 2445

You can use a stream:

private ArrayList<Boolean> changeThis(ArrayList<Integer> arr){
        return arr.stream().map(e -> (e == 1) ).collect( Collectors.toCollection( ArrayList::new ) );
}

Upvotes: 3

Related Questions