Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. class Foo {
  2. private Map<String, Object> data = new HashMap<>();
  3.  
  4. String build() {
  5. StringBuilder builder = new StringBuilder();
  6. builder.append("{");
  7.  
  8. Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator();
  9. while (it.hasNext()) {
  10. Map.Entry entry = it.next();
  11. builder.append(String.format(
  12. ""%s": "%s"", entry.getKey(), entry.getValue()
  13. ));
  14.  
  15. if (it.hasNext()) {
  16. builder.append(", ");
  17. }
  18. }
  19. builder.append("}");
  20.  
  21. return builder.toString();
  22. }
  23.  
  24. Foo a(Object value) {
  25. data.put("a", value);
  26. return this;
  27. }
  28. Foo a() {
  29. return a(null);
  30. }
  31.  
  32. Foo b(Object value) {
  33. data.put("b", value);
  34. return this;
  35. }
  36.  
  37. Foo c(Object value) {
  38. data.put("c", value);
  39. return this;
  40. }
  41. }
  42.  
  43. public static void main(String[] args) {
  44. System.out.println("text: " + new Foo().a(null).b(1).c("123").build());
  45. // text: {"a": "null", "b": "1", "c": "123"}
  46.  
  47. System.out.println("text: " + new Foo().build());
  48. // text: {}
  49.  
  50. System.out.println("text: " + new Foo().a().build());
  51. // text: {"a": "null"}
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement