简体   繁体   中英

Find items by property in JLIST

I have a JList peopleList populated with a objects of Person class

class Person
{
  private String name;
  private String age;

  private void setName(String value)
  {
    name = value;
  }

  private String getName()
  {
    return name;
  }
}

Current to find a person with name I do

public boolean personByNameExists(String name)
{
  for(int index = 0 ; index < peopleList .getModel().getSize() ; index ++)
  {
    Person pl = (Person) peopleList .getModel().getElementAt(index);

    if( p1.getName().equals(name))
    {
      return  true;
    }
  }
}

I am wondering if there is way to do the same operation with out going through the whole list. I am from .Net back ground and in C# I would use LINQ is there something similar in Java?

You're looking for a typical filter functionality.

I'd recommend you look at Google Guava's:

You can find more info here or even look at this SO question (your question is a duplicate):

Update: As kleopatra made me realize, you might be using a normal ListModel .

You could specifiy a custom model when creating your JList, that either:

  • implements a Collection or Iterable interface,
  • or provides a method to return a view of the data filtered by the property you want.

It depends a bit on the use-case. If you just want to find an entry on the model side, you can keep looping over your ListModel , or loop over the data structure behind the ListModel which can be a regular List implementation, and then you can use the methods suggested by haylem.

If you want to search on your JList , and present the search result visually to the user (for example highlight them and scroll to the relevant entry) I would highly recommend taking a look at the SwingX project which supports this out-of-the-box

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