-1

I am using the below method and need to use stream and lamdas in java 8.

public static void addMemberships(final int key, MembershipData[] members) throws SpiderException
  {
    HashMap<String, MembershipData> duplicates = new HashMap<>();
    for(MembershipData m: members) {
      duplicates.putIfAbsent(m.subjectOfCare, m);
    }
    members = duplicates.values().toArray(new MembershipData[0]);
    internalMembershipToolkit.verifyData(key, members);
}

I tried using members.forEach(duplicates.putIfAbsent(m.subjectOfCare, m)); but it didnt work. How can I replace the for loop with stream?

Holger
  • 285,553
  • 42
  • 434
  • 765
Codeninja
  • 322
  • 1
  • 4
  • 18

1 Answers1

3

You don't need putIfAbsent. You can stream over the elements of the array and collect them to a Map, using a merge function to get rid of duplicates.

Map<String, MembershipData> duplicates = 
    Arrays.stream(members)
          .collect(Collectors.toMap(m -> m.subjectOfCare,
                                    Function.identity(),
                                    (m1,m2)->m1));

Or, to include the conversion to array in the same statement:

members = 
    Arrays.stream(members)
          .collect(Collectors.toMap(m -> m.subjectOfCare,
                                    Function.identity(),
                                    (m1,m2)->m1))
          .values()
          .toArray(new MembershipData[0]);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • It works. Can you explain what m1 and m2 represents here? – Codeninja Jun 15 '20 at 07:12
  • 1
    @ShaviPathirana they represent two values of the Map (`MembershipData` instances) having the same key. (m1,m2)->m1 means that in case of two values having the same key, the first value will be kept in the Map and the second value will be discarded. – Eran Jun 15 '20 at 07:15
  • how about a `distinctByKey` approach for the values collected before the array conversion? – Naman Jun 15 '20 at 08:03
  • @Naman Where is `distinctByKey` defined (and in which Java version)? I'm not familiar with that method. – Eran Jun 15 '20 at 08:06
  • @Eran It's not an inbuilt capability of the JDK, but here is a [Q&A](https://stackoverflow.com/questions/23699371/java-8-distinct-by-property) illustrating it. – Naman Jun 15 '20 at 09:31