简体   繁体   中英

Python's generators similar in Java

I have python background so please allow me have my code in python.

In Java (Android) have an arrayList<customObject> . In each customObject corresponds a boolean (for visibility).

I want to perform operations as more efficient as possible to check the visibility boolean. In python I would create a generator.

Assuming my schema is :

list = [{"item": customObject, "visible": boolean}, {...}, {...}]
visible_matches = [x for x in list if x['visible']] 

for match in visible_matches: 
    dosomething(match)

or an alternative schema:

list = [[ customObject, boolean], [...], [...]]
visible_matches = [x for x in list if x[1]]

How could I perform the same in Java?

arrayList<arrayList<boolean,customObject>> or arrayList< SimpleEntry<"item",customObject>, SimpleEntry<"visible",boolean> >

look a really dirty solutions to me. Is there any simpler way to achieve this?

Use a java.util.Map<CustomObject, Boolean> which maps objects to its visible state.

EDIT Getting all visible items in a map:

Map<CustomObject, Boolean> items = ...;
List<CustomObject> visibleItems = new ArrayList<CustomObject>();

for (Map.Entry<CustomObject, Boolean> entry : items.entrySet()) {visibleItems
    CustomObject customObject = entry.getKey();
    Boolean objectVisible = entry.getValue();

    if (objectVisible) {
        visibleItems.add(customObject);
    }
}

I really do miss something like closures in Java...

Java doesn't have generators in the same sense that Python does (iterators are not exactly the same thing). Creating custom objects on the fly like you did in Python doesn't work either. Because Java is strongly typed, you must define your custom object before you can use it. Python is not strongly typed.

In a separate file, try this starting code. I named mine class MyCustomObject because it's inside MyCustomObject.java. The names have to match.

public class MyCustomObject {

    public boolean visible;

    // Constructor
    public MyCustomClass(boolean visible) {
        this.visible = visible;
    }

}

Now that you have a custom object, you can instantiate and manipulate it like this in your main class. I called mine class Main because again, it's in Main.java.

public class Main {

    public static void main(String[] args) {

        ArrayList<MyCustomObject> list = new ArrayList<>();
        list.Add(new MyCustomObject(true));
        list.Add(new MyCustomObject(false));
        list.Add(new MyCustomObject(true));
        list.Add(new MyCustomObject(true));

        ....

        for (MyCustomObject potentialMatch: list) {
            if(obj.visible) 
                doSomething(potentialMatch);
        }
    }

}

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