Last active
December 26, 2015 08:09
-
-
Save manuzhang/7120524 to your computer and use it in GitHub Desktop.
Filter out object with a value 'a' who appears more than once among all the objects
This file contains 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
package me.ifthiskills.map; | |
import java.util.HashMap; | |
import java.util.HashSet; | |
import java.util.Iterator; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Set; | |
public class FilterObject { | |
public int a = 0; | |
public FilterObject(int a) { | |
this.a = a; | |
} | |
public void setA(int a) { | |
this.a = a; | |
} | |
public int getA() { | |
return a; | |
} | |
public static void main(String[] args) { | |
// initialize | |
List<FilterObject> originalList = new LinkedList<FilterObject>(); | |
originalList.add(new FilterObject(2)); | |
originalList.add(new FilterObject(1)); | |
originalList.add(new FilterObject(2)); | |
originalList.add(new FilterObject(3)); | |
originalList.add(new FilterObject(0)); | |
originalList.add(new FilterObject(3)); | |
Map<Integer, List<FilterObject>> filterMap = | |
new HashMap<Integer, List<FilterObject>>(); | |
Set<Integer> moreThanOneSet = new HashSet<Integer>(); | |
// count the occurrence of 'a' | |
for (FilterObject object : originalList) { | |
int key = object.getA(); | |
if (filterMap.containsKey(key)) { | |
filterMap.get(key).add(object); | |
moreThanOneSet.add(key); | |
} else { | |
List<FilterObject> list = new LinkedList<FilterObject>(); | |
list.add(object); | |
filterMap.put(key, list); | |
} | |
} | |
// keep FilterObject with 'a' who appears more than once | |
List<FilterObject> filteredList = new LinkedList<FilterObject>(); | |
for (Iterator<Integer> iterator = moreThanOneSet.iterator(); iterator | |
.hasNext();) { | |
filteredList.addAll(filterMap.get(iterator.next())); | |
} | |
// print result | |
for (Iterator<FilterObject> iterator = filteredList.iterator(); iterator | |
.hasNext();) { | |
System.out.println(iterator.next().getA()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment