javasortedset

how to find an item in a SortedSet in Java


I have a Sorted Set in Java with an object with 2 strings, Name and Age. Name is unique.

Now I have the Name and I want to get the age based on the name.

I have my object:

SortedSet<Person> people;

That has 3 people inside: "John / 35", "James / 21" and "Maria /21"

Based on this, I want to check James age.

How can I do it? The only idea I have is just doing a for, but I guess it should be something easier.


Solution

  • I see two solutions there:

    1. If there really are just this two properties, you could simply convert that to a map, where the name is the key and the age is the value, ( Map<String, Integer> ageMap). Then you can quickly get the age by using ageMap.get("James");.

    Edit: To convert you can do this:

    Map<String, Integer> ageMap = new HashMap<>();
    for (Person p : people) {
       ageMap.put(p.getName(), p.getAge());
    }
    int jamesAges = ageMap.get("James");
    
    1. If you stay with the Set and the Person class, I would recommend using the streams:

      Optional findFirst = set.stream().filter(e -> e.getName().equals("James")).findFirst();

      if (findFirst.isPresent()) {

       int age = findFirst.get().getAge();
      

      }

    Internally, this will probably still use some kind of for, but the real implementation might be a bit more optimized.