0

I have following class in which I am going to store name and position of user,

public class NameAndPosition {

    private String name = "";
    private LatLng position = null;


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public LatLng getPosition() {
        return position;
    }
    public void setPosition(LatLng position) {
        this.position = position;
    }

}

And in my MainActivity class I have created an ArrayList of objects of class NameAndPostion,

ArrayList<NameAndPosition> LocSenders = new ArrayList<NameAndPosition>();

In somewhere in my code I want to check if LocSenders contains a user with a given name. I don't want to matter a position here. I just want to check with name in LocSenders ArrayList.

e.g. I have specified a name John then I want to retrieve those objects in ArrayList which has name John.

How to do that?

Thanks in advance.

4
  • I bet you wished Java had LINQ ;) On a serious note.. what have you tried? Commented Apr 2, 2015 at 15:28
  • I am trying with contains method of ArrayList class. But I am not getting what I want Commented Apr 2, 2015 at 15:29
  • Post the algorithm you have. So everyone can see. Commented Apr 2, 2015 at 15:30
  • @user370305 I disagree. This will make all NameAndPosition instances with identical name equal to each other, no matter of their position. This is a serious limitation that might not be acceptable. Commented Apr 2, 2015 at 15:50

2 Answers 2

3

Since Java 8, you can use the Stream API for things like that.

Collection<NameAndPosition> list = ...;
String name = ...;
boolean inList = list.stream().anyMatch(e -> name.equals(e.getName()));
Sign up to request clarification or add additional context in comments.

2 Comments

Plus one.. Not quite there.. but close enough :)
@weston Absolutely nothing. It was a weak dig at LINQ vs Stream API. I haven't used Java in 2 or more years but glad to see some progress.
2

You'll need to loop through them and look at each name:

public static boolean ListContainsName(List<NameAndPosition> list, String name) {
    for (NameAndPosition nandp : list)
       if (name.equals(nandp.getName()))
         return true;
    return false;
}

Usage:

if (ListContainsName(LocSenders, "John"))
  // then John is in list

Alternatively

If looking up by name is pretty common, have you considered a map:

Map<String, LatLng> sendersLocations = new HashMap<String, LatLng>();

Then looking up is easier and more efficient:

if (sendersLocations.containsKey("John"))
  // then John is in list

And getting position is just as easy:

LatLng pos = sendersLocations.get("John");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.