fork download
  1. /**
  2.  * Compact a list of objects Label, which is sorted on Label.amount
  3.  */
  4.  
  5. import java.util.*;
  6.  
  7. class Label {
  8. private final String id;
  9. private final double amount;
  10.  
  11. public Label(String id, double amount)
  12. {
  13. this.id = id;
  14. this.amount = amount;
  15. }
  16.  
  17. public String getId() {
  18. return this.id;
  19. }
  20.  
  21. public double getAmount() {
  22. return this.amount;
  23. }
  24.  
  25. public String toString() {
  26. return id + ": " + amount;
  27. }
  28. }
  29.  
  30. class Ideone {
  31. public static List<Label> compact(List<Label> l)
  32. {
  33. Set<String> ids = new HashSet<>();
  34. List<Label> toret = new ArrayList<>();
  35.  
  36. for(Label label: l) {
  37. if ( !ids.contains( label.getId() ) ) {
  38. ids.add( label.getId() );
  39. toret.add( label );
  40. }
  41. }
  42.  
  43. return toret;
  44. }
  45.  
  46. public static void compactInPlace(List<Label> l)
  47. {
  48. Set<String> ids = new HashSet<>();
  49.  
  50. for(int i = 0; i < l.size(); ++i) {
  51. if ( !ids.contains( l.get( i ).getId() ) ) {
  52. ids.add( l.get( i ).getId() );
  53. } else {
  54. l.remove( i );
  55. --i;
  56. }
  57. }
  58.  
  59. return;
  60. }
  61.  
  62. public static void main(String[] args)
  63. {
  64. ArrayList<Label> l = new ArrayList<>();
  65.  
  66. l.add( new Label( "1742", 10 ) );
  67. l.add( new Label( "1742", 11 ) );
  68. l.add( new Label( "1647", 12 ) );
  69. l.add( new Label( "4217", 13 ) );
  70. l.add( new Label( "1647", 14 ) );
  71. l.add( new Label( "1742", 15 ) );
  72.  
  73. compactInPlace( l );
  74. System.out.println( l );
  75. }
  76. }
  77.  
Success #stdin #stdout 0.09s 320320KB
stdin
Standard input is empty
stdout
[1742: 10.0, 1647: 12.0, 4217: 13.0]