Created
February 10, 2015 15:56
-
-
Save xcv58/c65c896fba48310ce1d1 to your computer and use it in GitHub Desktop.
Custom Hash implementation with Java 8 Stream
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
import java.util.*; | |
import java.util.stream.*; | |
public class CustomHash { | |
public class Entry { | |
List<Object> list; | |
public Entry() { | |
list = new ArrayList<Object>(); | |
} | |
public void add(Object o) { | |
list.add(o); | |
} | |
public int hashCode() { | |
int hash = 0; | |
for (Object o : list) { | |
hash += o.hashCode(); | |
} | |
int h = list.stream() | |
.mapToInt(Object::hashCode) | |
.sum(); | |
return h; | |
// Above codes just show that stream is same as for loop. | |
// return list.stream() | |
// .mapToInt(Object::hashCode) | |
// .sum(); | |
} | |
public boolean equals(Object object) { | |
Entry entry = (Entry) object; | |
return entry.list.size() == this.list.size() && this.equals(entry.list); | |
} | |
private boolean equals(List<Object> compareList) { | |
boolean result = true; | |
for (int i = 0; result && i < this.list.size(); i++) { | |
Object o1 = list.get(i); | |
Object o2 = compareList.get(i); | |
result &= o1.equals(o2); | |
} | |
return result; | |
} | |
} | |
private void process() { | |
HashSet<Entry> set = new HashSet<Entry>(); | |
Entry e1 = new Entry(); | |
Entry e2 = new Entry(); | |
Entry e3 = new Entry(); | |
e1.add(new Integer(1)); | |
e2.add(new Integer(1)); | |
e3.add(new Integer(1)); | |
e1.add(new Long(Integer.MAX_VALUE)); | |
e2.add(new Long(Integer.MAX_VALUE)); | |
e3.add(new Long(Integer.MAX_VALUE)); | |
e1.add(new Double(1.000)); | |
e2.add(new Double(1.0)); | |
e3.add(new Double(1.0)); | |
e1.add(new String("123")); | |
e2.add(new String("123")); | |
e3.add(new String("123")); | |
e1.add(new Entry()); | |
e2.add(new Entry()); | |
e3.add(new Entry()); | |
e1.add(new HashMap(128)); | |
e2.add(new HashMap()); | |
e3.add(new HashMap()); | |
e1.add(new HashSet(32)); | |
e2.add(new HashSet()); | |
e3.add(new HashSet()); | |
e1.add(new ArrayList(1024)); | |
e2.add(new ArrayList()); | |
e3.add(new ArrayList()); | |
set.add(e1); | |
set.add(e2); | |
set.add(e3); | |
System.out.println(set.size()); | |
} | |
public static void main(String[] args) { | |
CustomHash test = new CustomHash(); | |
test.process(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment