Search the Java collection. Why is it so hard?

Is there any reasonable explanation why finding an item in a Java collection is so difficult? For example, suppose I have:

ArrayList<People> listPeople = new ArrayList<People>();

public class People
{
   public String name;
   public String age;
   //some other code here
}

You had an idea ... Now, if I want to get from the Person list with the given name, say, "Anthares", I have to do so much work: create a new person named "Anthares", maybe initiate it with some other data , predefine my equals method for the Person class, then call listPeople.IndexOf (tempPerson) and finally get the returned int and do listPeople [idx]

Why all this pain. For example, in C # I can make a linq expression, pass it to the correct method of my collection and this. One simple line of code.

+3
7

, :

Person found = null;
for (Person person : listPeople)
{
    if ("Anthares".equals(person.name))
    {
        found = person;
        break;
    }
}
// Check for found == null etc

, , LINQ, , # -. - Java, :

Person person = FakeLinq.findFirst(listPeople, new Predicate<Person>() {
    @Override boolean matches(Person person) {
        return person.name.equals("Anthares");
    }
});

# .

Java 7 (,!) - -, Java.

+6
for(Person p : listPeople) {
  if(p.name.equals("Anthares")) {
    found = p;
    break;
  }
}

, # jdk7.

+2

, Java, . Collection.indexOf(), , "if (want.equals(collectionMember)", "if (collectionMember.equals(want))".

, , "MyObject.equals(String)" "MyObject.equals(Integer)", , , ...

public boolean equals(String wantname)
{
  return this.name.equals(wantname);
}

"if (want.equals(collectionMember)" ), , Java String "equals (MyObject)", . , .

, , . , , , , HashMap ?

+1

lambdaj , :

select(listPeople, having(on(Person.class).getName(), equalTo("Anthares"))
+1

, HashMap/HashTable .

linq Java, :)

0

, , ( Java API)

, HashMap, , , , "" .

java, / .

0

Source: https://habr.com/ru/post/1732689/


All Articles