Reputation: 331
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 );
}
Upvotes: 0
Views: 2823
Reputation: 665
The method public static <T> List<T> searchIn( List<T> list , Matcher<T> m )
returns List<T>
, in your case Person if you want to get person age
try result.stream().map(Person::getAge).forEach(System.out::println);
Upvotes: 2
Reputation: 10964
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
.
Upvotes: 4