Skip to content

Instantly share code, notes, and snippets.

@bufferings
Last active March 21, 2018 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bufferings/c9835f7a3b6c4f2b8780eecae9d32fa5 to your computer and use it in GitHub Desktop.
Save bufferings/c9835f7a3b6c4f2b8780eecae9d32fa5 to your computer and use it in GitHub Desktop.
Java10で匿名クラス遊び
import java.util.List;
import static java.util.stream.Collectors.toList;
// I've referenced this post:
// https://developer.oracle.com/java/jdk-10-local-variable-type-inference
public class Main {
public static void main(String[] args) {
var products = List.of(
new Product("Apple", 100, 3),
new Product("Orange", 50, 10),
new Product("Peach", 200, 6));
var reports = products.stream()
.map(p -> new Object() {
String name = p.name;
int total = p.price * p.count;
}).collect(toList());
reports.forEach(r ->
System.out.println("name = " + r.name + ", total = " + r.total));
}
private static class Product {
String name;
int price;
int count;
Product(String name, int price, int count) {
this.name = name;
this.price = price;
this.count = count;
}
}
}
@bufferings
Copy link
Author

name = Apple, total = 300
name = Orange, total = 500
name = Peach, total = 1200

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment