Last active
March 1, 2018 21:27
-
-
Save donhenton/1474c01e5d517e340c7d52e7dcac42d4 to your computer and use it in GitHub Desktop.
Find a duplicate in a list and create unique map keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.HashMap; | |
| import java.util.List; | |
| import java.util.Map; | |
| import java.util.Map.Entry; | |
| import java.util.TreeMap; | |
| import java.util.stream.Collectors; | |
| import java.util.stream.Stream; | |
| import javafx.util.Pair; | |
| List<Pair<String,String>> pairList = new ArrayList<>(); | |
| pairList.add(new Pair("alpha","100")); | |
| pairList.add(new Pair("alpha","200")); | |
| pairList.add(new Pair("alpha","300")); | |
| pairList.add(new Pair("beta","101")); | |
| pairList.add(new Pair("beta","102")); | |
| pairList.add(new Pair("gamma","1000")); | |
| List<String> duplicateKeys = pairList.stream().collect(Collectors.groupingBy(Pair::getKey)) | |
| .entrySet().stream().filter(list -> list.getValue().size() > 1) | |
| .map(Map.Entry::getKey) | |
| .collect(Collectors.toList()); | |
| HashMap<String,Integer> counterMap = new HashMap<>(); | |
| duplicateKeys.forEach(k -> { | |
| counterMap.put(k, 1); | |
| }) ; | |
| Map<String, Object> options = new TreeMap<>(); | |
| pairList.forEach(p -> { | |
| if (counterMap.keySet().contains(p.getKey())) { | |
| int ct = counterMap.get(p.getKey()); | |
| String v = p.getValue(); | |
| String k = p.getKey()+ " ("+ct+")"; | |
| ct = ct + 1; | |
| counterMap.put(p.getKey(),ct); | |
| options.put(k, v); | |
| } | |
| else { | |
| options.put(p.getKey(), p.getValue()); | |
| } | |
| }); | |
| // options now contains key: 'Alpha (1)' value: 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment