Skip to content

Instantly share code, notes, and snippets.

@gkhays
Forked from milingo/CollectionUtils.java
Last active April 3, 2016 16:29
Show Gist options
  • Save gkhays/19cd5f09ac64035e3527 to your computer and use it in GitHub Desktop.
Save gkhays/19cd5f09ac64035e3527 to your computer and use it in GitHub Desktop.
Java Collections

Java Collections

Trying to remember why I did this...

static boolean matchFriend(List<String> friendList, String candidate) {
	for (String s : friendList) {
		if (s.equals(candidate)) {
			return true;
		}
	}
	return false;
}

static boolean evaluateAsFriends(Map<String, List<String>> friendMap, String a, String b) {
	for (Map.Entry<String, List<String>> entry : friendMap.entrySet()) {
		if (entry.getKey().equals(a)) {
			return matchFriend(entry.getValue(), b);
		}
	}
	return false;
}

static void printOutput(Map<String, List<String>> friendMap, String friend, String candidate) {
	long end;
	long start = System.currentTimeMillis();
	System.out.print(String.format("Evaluating %s and %s: ", friend, candidate));
	boolean match = evaluateAsFriends(friendMap, friend, candidate);
	System.out.print(match);
	end = System.currentTimeMillis();
	System.out.println(String.format(" ---> Results in %d ms", (end - start)));
}
	
public static void main(String[] args) {
	Map<String, List<String>> friendMap = new HashMap<String, List<String>>();
	friendMap.put("Bob", Arrays.asList("Ann", "Sally", "Sue"));
	friendMap.put("Ann", Arrays.asList("Bob", "Fred"));
	friendMap.put("Fred", Arrays.asList("Tom", "Cathy", "John", "Ann"));
	
	printOutput(friendMap, "Bob", "Sally");
	printOutput(friendMap, "Bob", "Fred");
	printOutput(friendMap, "Ann", "Tom");
}

Output:

Evaluating Bob and Sally: true ---> Results in 4 ms
Evaluating Bob and Fred: false ---> Results in 0 ms
Evaluating Ann and Tom: false ---> Results in 0 ms

References

How to efficiently iterate over each Entry in a Map? (Top voted answer for above: answered by @ScArcher2).
Example of using iterator and generics:

Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Map.Entry<String, String> entry = entries.next();
  String key = entry.getKey();
  String value = entry.getValue();
  // ...
}

Or as suggested by Steve Kuo and @ComFreek

for (Iterator<Map.Entry<K, V>> entries = myMap.entrySet().iterator(); entries.hasNext(); ) {
	Map.Entry<K, V> entry = entries.next();
}
You should put Iterator in a for loop to limit its scope. – Steve Kuo Feb 17 '12 at 20:32
@StudioWorks for (Iterator> entries = myMap.entrySet().iterator(); entries.hasNext(); ) { Map.Entry entry = entries.next(); }. By using that construct we limit the scope of (visibility of the variable) entries to the for loop. – ComFreek Mar 13 '15 at 16:33

Lambda Expression Java 8

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
// Init
new String[]{"a", "b"}
List<String> list = new ArrayList<String>(
Arrays.asList("String A", "String B", "String C")
);
Map<String, Owner> owners = new HashMap<String, Owner>() {{
put("no-money", createOwnerWithoutMoney());
}};
Collection<String> collection = list;
// convert
new HashSet<>(Arrays.asList(new String[]{"a", "b"}));
// utils
public static <T> boolean any(Collection<T> collection, ConditionalFunction<T> f) {
if (collection != null) {
for (T e : collection) {
if (f.fulfills(e)) {
return true;
}
}
}
return false;
}
// find
public <T> Collection<JSONObject> find(
Collection<JSONObject> collection, String val) {
List<JSONObject> l = new LinkedList<JSONObject>();
for (JSONObject j : collection) {
if (this.matches(j, val)) {
l.add(j);
}
}
return l;
}
@Override
public boolean matches(JSONObject jsonObj, String val) {
try {
return jsonObj.getString("id").equals(val);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public interface FindAll<T> {
public boolean matches(T obj, String val);
}
public void sort() {
Collections.sort(jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a1, JSONObject a2) {
int result = 0;
try {
result = a1.getString("id").compareTo(a2.getString("id"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
});
}
// For Java 8, you could to the above the following way; see
// https://jaxenter.com/why-is-java-still-changing-119535.html
public void sort() {
jsonList.sort(comparing(JSONObject.getString()));
}
public static <T> boolean isEmpty(Collection<T> list) {
return list == null || list.isEmpty();
}
// utils tests
public void testAny(List<Integer> numbers, boolean expected) throws Exception {
ConditionalFunction<Integer> isEven = new ConditionalFunction<Integer>() {
public boolean fulfills(Integer number) {
return number % 2 == 0;
}
};
assertTrue(CollectionUtils.any(numbers, isEven) == expected);
}
public <T extends Shape> void addIfPretty(List<T> shapes, T shape) {
if (shape.isPretty()) {
shapes.add(shape);
}
}
import java.text.MessageFormat;
String pattern = "I have {0} apples";
String message = MessageFormat.format(pattern, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment