-4

I have a List of objects. each object has two properties.

  • name
  • idSet

Example:

 1. name = "CH2OH"       idSet = "223"
 2. name = "CH2CH2OH"    idSet = "255,310"
 3. name = "CH2OH"       idSet = "223,256"
 4. name = "CH2OH"       idSet = "223,256,295"

1,3 and 4 have same name but different idList. But 3 contains 1's idList item + a new id, and 4 has 3's idList + a new one.

I want to get a list or stream, with the name as a key and idList as it's value. However, the idList should always get maximum

expected out put according to the example

 - name = "CH2CH2OH"     idSet = "255,310"
 - name = "CH2OH"        idSet = "223,256,295"

How can I get it by using java 8. I have tried this. but the problem is it is getting distinct stream by considering only one property. Its randomly getting one and eliminate others. I want to get stream by considering two properties.Thanks

Community
  • 1
  • 1
Kaushali de Silva
  • 241
  • 1
  • 3
  • 9
  • "How can I get it by using java 8"? ... Well, by writing code. If you do not know how to do that, then go and work on some tutorials. There are tons of them. This question is either unclear or too broad. – Seelenvirtuose Mar 06 '17 at 07:25
  • @Seelenvirtuose :I have tried this[](http://stackoverflow.com/questions/23699371/java-8-distinct-by-property) one but the problem is its getting distinct stream by considering only one property. Its randomly getting one and eliminate others. I want to get stream by considering two properties. – Kaushali de Silva Mar 06 '17 at 07:36
  • Please post a [MCVE] version of your code – c0der Mar 06 '17 at 07:38
  • You really need to be more precise. What kind of stream to you get? Apparently you are not talking about a `java.util.stream.Stream`... – dpr Mar 06 '17 at 07:48
  • I thought it was a pretty clear question... This was actually a good question too. – Nick Ziebert Mar 06 '17 at 08:32

1 Answers1

1

Try something like this. I found this solution in a YT video I watched yesterday. Go to about 1:58:30

https://www.youtube.com/watch?v=1OpAgZvYXLQ

List<MyObjects> myList = createObjects();


Map<String, Optional<String>> myMappedList = myList.stream()
             .collect(Collectors.groupingBy(MyObjects::getName, 
                     Collectors.mapping(MyObjects::getidSet, 
                         Collectors.maxBy((a, b) -> a.toString().length() - b.toString().length()))));

//Here's the output with your example (Using toString override in MyObjects Class):

System.out.println(myMappedList);

{CH2OH=Optional[223,256,295], CH2CH2OH=Optional[255,310]}

By "max", the comparator is looking for the idset with the longest string length.

Hope this helps, I thought this was a good question. Venkat Subramaniam thought it important enough to talk about...

Nick Ziebert
  • 1,258
  • 1
  • 9
  • 17