Modify Matching Objects using Java Streams

Viewed 38

Suppose I have the following structure:

class Person {
  public String name;
  public double netWorth;
  public Person(String name, String netWorth) { this.name = name; this.netWorth = netWorth; }
}

and following stream:

Stream.of(
  new Person("Jeff Bezos", 12),
  new Person("Jeff Bezos", 165_345_678_910), 
  new Person("Jeff Bezos", 1_234),
  new Person("Jeff Bezos(1)", 1_234),
  new Person("Jeff Bezos(1)(2)", 42),
  new Person("Bill Gates", 130_000_000_000));

by using Java Streams API I want to transform stream above so that:

  • Person-s with same names should receive different strings (by adding (i)) in the end of the name
  • no cycles / if statements / interim stream terminators
  • order of names does not matter, e.g. out of two Person-s with same names either of two can receive (1) suffix

e.g. to a following map:

new HashMap<String, Double>() {{
  put("Jeff Bezos", 12);
  put("Jeff Bezos(1)(1)(1)", 165_345_678_91);
  put("Jeff Bezos(1)(1)(2)", 1_234);
  put("Jeff Bezos(1)", 1_234);
  put("Jeff Bezos(1)(2)", 42);
  put("Bill Gates", 130_000_000_000);
}};

P.S. Complicatoion, order of Persons matter, person with the highest net worth should receive the cleanest name, e.g. with min suffixes etc:

new HashMap<String, Double>() {{
  put("Jeff Bezos", 165_345_678_91);
  put("Jeff Bezos(1)(1)(1)", 1_234);
  put("Jeff Bezos(1)(1)(2)", 12);
  put("Jeff Bezos(1)(2)", 42);
  put("Jeff Bezos(1)", 1_234);
  put("Bill Gates", 130_000_000_000);
}};
0 Answers
Related