简体   繁体   中英

Get specific value of List Java

You can run in online java compiler here https://www.codechef.com/ide choose java8.

Here is my code to search other value: I want to print just '18' when I search 'Java'. This code will return : [Person(Java,18)] My question how to print just '18'?

import java.util.*;
class LinearSearchDemo { 
  public static void main (String[] args) { 
      List<Person> list = Arrays.asList(
                                  Person.create("Oscar", 16),
                                  Person.create("Oei", 17),
                                  Person.create("Java", 18)
                          );

      List<Person> result = searchIn( list, 
              new Matcher<Person>() { 
                  public boolean matches( Person p ) { 
                      return p.getName().equals("Java");
              }});

      System.out.println( result );
  }
  public static <T> List<T> searchIn( List<T> list , Matcher<T> m ) { 
      List<T> r = new ArrayList<T>();
      for( T t : list ) { 
          if( m.matches( t ) ) { 
              r.add( t );
          }
      }
      return r;
  }
}

class Person { 
  String name;
  int age;

  String getName(){ 
      return name;
  }
  int getAge() { 
      return age;
  }
  static Person create( String name, int age ) { 
      Person p = new Person();
      p.name = name;
      p.age = age;
      return p;
  }
  public String toString() { 
      return String.format("Person(%s,%s)", name, age );
  }    
}
interface Matcher<T> { 
  public boolean matches( T t );
}

You are printing result to stdout . The objects in this list are of type Person . That is the Person.toString() method is used to get a string representation of result .

As mentioned in the comments either change the toString method of Person to just return the value of age or iterate over the result and write the value of age to stdout .

方法public static <T> List<T> searchIn( List<T> list , Matcher<T> m )返回List<T> ,在这种情况下,如果要获取人员年龄,请返回result.stream().map(Person::getAge).forEach(System.out::println);

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