Java 8 Method Reference Java
public class ObjectRefExample { DataService dataService = new DataService(); public static void main(String[] args) { ObjectRefExample example = new ObjectRefExample(); example.showUsersInfo(); } private void showUsersInfo() { List<String> userIds = dataService.getAllUserIds(); //method ref on instance, using this userIds.forEach(this::displayUserInfo); } private void displayUserInfo(String id) { System.out.println("User Info for id :" + id); //method ref on dataService instance display(id, dataService::getUserNameById); display(id, dataService::getUserAddressById); System.out.println("------------------------"); } private void display(String id, Function<String, ?> theConsumer) { System.out.println(theConsumer.apply(id)); }}
@PostConstruct private void postConstruct () { Stream.iterate(1L, a -> a + 1) .limit(10) .forEach(this::createCustomer); } private void createCustomer (Long id) { DataFactory df = new DataFactory(); Customer c = new Customer(); c.setName(df.getName()); c.setId(id); Address a = new Address(); a.setStreet(df.getNumberText(4)+" "+df.getStreetName()); a.setCity(df.getCity()); a.setCounty(df.getItem(Locale.getISOCountries())); a.setZipCode(df.getNumberText(5)); c.setAddress(a); customerMap.put(c.getId(), c); }