We can transform java objects using guava .
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
public class TransformExample {
public static void main(String[] args) {
ArrayList<User> users = new ArrayList<User>();
users.add(new User("java", 10));
users.add(new User("c", 30));
users.add(new User("php", 40));
users.add(new User("html", 100));
users.add(new User("javascript", 500));
users.add(new User("css", 300));
Function<User, Long> userIdsConvert = new Function<User, Long>() {
public Long apply(User user) {
return user.getUserId();
}
};
List<Long> userIds = Lists.transform(users, userIdsConvert);
for (Long id : userIds) {
System.out.println("userId is=" + id);
}
}
}
class User {
private String name;
private long userId;
public User(String name, long userId) {
super();
this.name = name;
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
Output:
userId is=10
userId is=30
userId is=40
userId is=100
userId is=500
userId is=300
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
public class TransformExample {
public static void main(String[] args) {
ArrayList<User> users = new ArrayList<User>();
users.add(new User("java", 10));
users.add(new User("c", 30));
users.add(new User("php", 40));
users.add(new User("html", 100));
users.add(new User("javascript", 500));
users.add(new User("css", 300));
Function<User, Long> userIdsConvert = new Function<User, Long>() {
public Long apply(User user) {
return user.getUserId();
}
};
List<Long> userIds = Lists.transform(users, userIdsConvert);
for (Long id : userIds) {
System.out.println("userId is=" + id);
}
}
}
class User {
private String name;
private long userId;
public User(String name, long userId) {
super();
this.name = name;
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
Output:
userId is=10
userId is=30
userId is=40
userId is=100
userId is=500
userId is=300
No comments:
Post a Comment