Search Results

Search found 34 results on 2 pages for 'treeset'.

Page 1/2 | 1 2  | Next Page >

  • Treeset to order elements in descending order

    - by Gaurav Saini
    Here is the piece of code that I have used for Java 5.0 TreeSet<Integer> treeSetObj = new TreeSet<Integer>( Collections.reverseOrder() ) ; Collections.reverseOrder() is used to obtain a comparator in order to reverse the way the elements are stored and iterated. Is there a more optimized way of doing it?

    Read the article

  • Java's TreeSet equivalent in Python?

    - by viksit
    I recently came across some Java code that simply put some strings into a Java TreeSet, implemented a distance based comparator for it, and then made its merry way into the sunset to compute a given score to solve the given problem. My questions, Is there an equivalent data structure available for Python? The Java treeset looks basically to be an ordered dictionary that can use a comparator of some sort to achieve this ordering. I see there's a PEP for Py3K for an OrderedDict, but I'm using 2.6.x. There are a bunch of ordered dict implementations out there - anyone in particular that can be recommended? Thanks.

    Read the article

  • Why does Java's TreeSet not specify that its type parameter must extend Comparable?

    - by Tarski
    e.g. The code below throws a ClassCastException when the second Object is added to the TreeSet. Couldn't TreeSet have been written so that the type parameter can only be a Comparable type? i.e. TreeSet would not compile because Object is not Comparable. That way generics actually do their job - of being typesafe. import java.util.TreeSet; public class TreeSetTest { public static void main(String [] args) { TreeSet<Object> t = new TreeSet<Object>(); t.add(new Object()); t.add(new Object()); } }

    Read the article

  • find words in a hashset or treeset?

    - by icelated
    I am piping in a file and storing it into a treeset. I am trying to count unique words.. I am placing words that i dont want into a hashset. "a","the", "and" I want to check to see if the file contains those words, before i place them into the TreeSet.. i know i need some sort of if(word == find) ? i just dont know how to do it.. Sorry about formatting. its hard to get it correct after you paste. this is what i have.. import java.util.Scanner; import java.util.ArrayList; import java.util.TreeSet; import java.util.Iterator; import java.util.HashSet; public class Project1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String word; String grab; int count = 0; int count2 =0; int count3 =0; int count4 =0; int number; TreeSet<String> a = new TreeSet<String>(); HashSet<String> find = new HashSet<String>(); System.out.println("Project 1\n"); find.add("a"); find.add("and"); find.add("the"); while (sc.hasNext()) { word = sc.next(); word = word.toLowerCase(); for(int i = 0; i < word.length(); i++ ) { if(Character.isDigit(word.charAt(i))) { count3++; } } //if( a.contains("a") ) //|| word.matches("and") || word.matches("the")|| word.contains("$")) //{ // count2++; // } a.add(word); if (word.equals("---")) { break; } } System.out.println("a size"); System.out.println(a.size()); // count = count2 - count; System.out.println("unique words"); System.out.println(a.size() - count2 - count3); System.out.println("\nbye..."); } }

    Read the article

  • List to TreeSet conversion produces: "java.lang.ClassCastException: MyClass cannot be cast to java.l

    - by Chuck
    List<MyClass> myclassList = (List<MyClass>) rs.get(); TreeSet<MyClass> myclassSet = new TreeSet<MyClass>(myclassList); I don't understand why this code generates this: java.lang.ClassCastException: MyClass cannot be cast to java.lang.Comparable MyClass does not implement Comparable. I just want to use a Set to filter the unique elements of the List since my List contains unncessary duplicates.

    Read the article

  • problem while removing an element from the TreeSet

    - by harshit
    I am doing the following class RuleObject implements Comparable{ @Override public String toString() { return "RuleObject [colIndex=" + colIndex + ", probability=" + probability + ", rowIndex=" + rowIndex + ", rule=" + rule + "]"; } String rule; double probability; int rowIndex; int colIndex; public RuleObject(String rule, double probability) { this.rule = rule; this.probability = probability; } @Override public int compareTo(Object o) { RuleObject ruleObj = (RuleObject)o; System.out.println(ruleObj); System.out.println("---------------"); System.out.println(this); if(ruleObj.probability > probability) return 1; else if(ruleObj.probability < probability) return -1; else{ if(ruleObj.colIndex == this.colIndex && ruleObj.rowIndex == this.rowIndex && ruleObj.probability == this.probability && ruleObj.rule.equals(this.rule)) return 0; } return 1; } } And I have a TreeSet containing elements of RuleObject. I am trying to do the following : System.out.println(sortedHeap.size()); RuleObject ruleObj = sortedHeap.first(); sortedHeap.remove(ruleObj); System.out.println(sortedHeap.size()); I can see that the size of set remains same. I am not able to understand why is it not being deleted. Also while deleting I could see compareTo method is called. But it is called for only 3 object whereas in set there are 8 objects. Thanks

    Read the article

  • Sorted sets and comparators

    - by Jack
    Hello, I'm working with a TreeSetthat is meant to store pathfind locations used during the execution of a A* algorithm. Basically until there are "open" elements (still to be exhaustively visited) the neighbours of every open element are taken into consideration and added to a SortedSetthat keeps them ordered by their cost and heuristic cost. This means that I have a class like: public class PathTileInfo implements Comparable<PathTileInfo> { int cost; int hCost; final int x, y; @Override public int compareTo(PathTileInfo t2) { int c = cost + hCost; int c2 = t2.cost + t2.hCost; int costComp = c < c2 ? -1 : (c > c2 ? 1: 0); return costComp != 0 ? costComp : (x < t2.x || y < t2.y ? -1 : (x > t2.x || y > t2.y ? 1 : 0)); } @Override public boolean equals(Object o2) { if (o2 instanceof PathTileInfo) { PathTileInfo i = (PathTileInfo)o2; return i.cost + i.hCost == cost + hCost && x == i.x && y == i.y; } return false; } } In this way first the total cost is considered, then, since a total ordering is needed (consistency with equals) a ordering according to the x,y coordinate is taken into account. This should work but simply it doesn't, if I iterate over the TreeSet during the algorithm execution like in for (PathTileInfo t : openSet) System.out.print("("+t.x+","+t.y+","+(t.cost+t.hCost)+") "); I get results in which the right ordering is not kept, eg: (7,7,6) (7,6,7) (6,8,6) (6,6,7) (5,8,7) (5,7,7) (6,7,6) (6,6,7) (6,5,7) (5,7,7) (5,5,8) (4,7,7) (4,6,8) (4,5,8) is there something subtle I am missing? Thanks!

    Read the article

  • Why is TreeSet<T> an internal type in .NET?

    - by Justin Niessner
    So, I was just digging around Reflector trying to find the implementation details of HashSet (out of sheer curiosity based on the answer to another question here) and noticed the following: internal class TreeSet<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback Without looking too deep into the details, it looks like a Self-Balancing Binary Search Tree. My question is, is there anybody out there with the insight as to why this class is internal? Is it simply because the other collection types use it internally and hide the complexities of a BST from the general masses...or am I way off base?

    Read the article

  • Set intersection of two strings

    - by user1785712
    import java.util.*; class set { public static void main(String args[]) { TreeSet<Character> t1 = new TreeSet<Character>(); TreeSet<Character> t2 = new TreeSet<Character>(); String s1 = "Ambitab bachan"; String s2 = "Ranjikanth"; for(char c1:s1.toCharArray()) t1.add(c1); for(char c2:s2.toCharArray()) t2.add(c2); t2.retainAll(t1); System.out.println(t2); } } this program find the common character in two different string. in this program Treeset is used to store the value and retainAll() method is used to find the common characters. can anybody help me reduce the line of coding.thanks in advance

    Read the article

  • Null pointer exception on .iterator() call

    - by Peter
    I'm getting a strange NullPointerException, evidently thrown by the following line of code: Iterator<Note> it = notes.iterator(); I've checked, and at the time the java.util.TreeSet notes is always non-null (with 15 elements). The TreeSet API says nothing about iterator() throwing NullPointerExceptions. What else could be going here?

    Read the article

  • A good Sorted List for Java

    - by Phuong Nguyen de ManCity fan
    I'm looking for a good sorted list for java. Googling around give me some hints about using TreeSet/TreeMap. But these components is lack of one thing: random access to an element in the set. For example, I want to access nth element in the sorted set, but with TreeSet, I must iterate over other n-1 elements before I can get there. It would be a waste since I would have upto several thousands elements in my Set. Basically, I'm looking for some thing similar to a sorted list in .NET, with ability to add element fast, remove element fast, and have random access to any element in the list. Has this kind of sorted list implemented somewhere? Thanks.

    Read the article

  • Searching in a TreeMap (Java)

    - by Kronen
    I need to do a search in a map of maps and return the keys this element belong. I think this implementation is very slow, can you help me to optimize it?. I need to use TreeSet and I can't use contains because they use compareTo, and equals/compareTo pair are implemented in an incompatible way and I can't change that. (sorry my bad english) Map m = new TreeSet(); public String getKeys(Element element) { for(Entry e : m.entrySet()) { mapSubKey = e.getValue(); for(Entry e2 : mapSubKey.entrySet()) { setElements = e2.getValue(); for(Element elem : setElements) if(elem.equals(element)) return "Key: " + e.getKey() + " SubKey: " + e2.getKey(); } } }

    Read the article

  • Hibernate: order multiple one-to-many relations

    - by Markos Fragkakis
    I have a search screen, using JSF, JBoss Seam and Hibernate underneath. There are columns for A, B and C, where the relations are as follows: A (1< -- ) B (1< -- ) C A has a List< B and B has a List< C (both relations are one-to-many). The UI table supports ordering by any column (ASC or DESC), so I want the results of the query to be ordered. This is the reason I used Lists in the model. However, I got an exception that Hibernate cannot eagerly fetch multiple bags (it considers both lists to be bags). There is an interesting blog post here, and they identify the following solutions: Use @IndexColumn annotation (there is none in my DB, and what's more, I want the position of results to be determined by the ordering, not by an index column) Fetch lazily (for performance reasons, I need eager fetching) Change List to Set So, I changed the List to Set, which by the way is more correct, model-wise. First, if don't use @OrderBy, the PersistentSet returned by Hibernate wraps a HashSet, which has no ordering. Second, If I do use @OrderBy, the PersistentSet wraps a LinkedHashSet, which is what I would like, but the OrderBy property is hardcoded, so all other ordering I perform through the UI comes after it. I tried again with Sets, and used SortedSet (and its implementation, TreeSet), but I have some issues: I want ordering to take place in the DB, and not in-memory, which is what TreeSet does (either through a Comparator, or through the Comparable interface of the elements). Second, I found that there is the Hibernate annotation @Sort, which has a SortOrder.UNSORTED and you can also set a Comparator. I still haven't managed to make it compile, but I am still not convinced it is what I need. Any advice?

    Read the article

  • Consistent Equals() results, but inconsistent TreeMap.containsKey() result

    - by smessing
    I have the following object Node: private class Node implements Comparable<Node>(){ private String guid(); ... public boolean equals(Node o){ return (this == o); } public int hashCode(){ return guid.hashCode(); } ... } And I use it in the following TreeMap: TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>(); Now, the tree map is used in a class called Graph to store nodes currently in the graph, along with a set of their edges (from the class Edge). My problem is when I try to execute: public containsNode(n){ for (Node x : nodes.keySet()) { System.out.println("HASH CODE: "); System.out.print(x.hashCode() == n.hashCode()); System.out.println("EQUALS: "); System.out.print(x.equals(n)); System.out.println("CONTAINS: "); System.out.print(nodes.containsKey(n)); System.out.println("N: " + n); System.out.println("X: " + x); } } I sometimes get the following: HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo Anyone have an idea as to what I'm doing wrong? I'm still new to all this, so I apologize in advance if I'm overlooking something simple (I know hashCode() doesn't really matter for TreeMap, but I figured I'd include it).

    Read the article

  • Add a new element to a SortedSet

    - by arjacsoh
    Can someone explain me why this code compiles and runs fine, despite the fact that SortedSet is an interface and not a concrete class: public static void main(String[] args) { Integer[] nums = {4, 7, 8, 14, 45, 33}; List<Integer> numList = Arrays.asList(nums); TreeSet<Integer> numSet = new TreeSet<Integer>(); numSet.addAll(numList); SortedSet<Integer> sSet = numSet.subSet(5, 20); sSet.add(17); System.out.println(sSet); } It prints normally the result: [7, 8, 14, 17] Furthermore, my wonder is heightened by the fact that the SortedSet cannot be instansiated (expectedly). This line does not compile: SortedSet<Integer> sSet = new SortedSet<Integer>(); However, if I try the code: public static void main(String[] args) { Integer[] nums = {4, 7, 8, 14, 45, 33}; List<Integer> numList = Arrays.asList(nums); numList.add(56); System.out.println(numList); } it throws an UnsupportedOperationException. I reckon, this comes from the fact that List is an interface and cannot be handled as a concrete class. What is true about SortedSet?

    Read the article

  • Why does using Collections.emptySet() with generics work in assignment but not as a method parameter

    - by Karl von L
    So, I have a class with a constructor like this: public FilterList(Set<Integer> labels) { ... } and I want to construct a new FilterList object with an empty set. Following Joshua Bloch's advice in his book Effective Java, I don't want to create a new object for the empty set; I'll just use Collections.emptySet() instead: FilterList emptyList = new FilterList(Collections.emptySet()); This gives me an error, complaining that java.util.Set<java.lang.Object> is not a java.util.Set<java.lang.Integer>. OK, how about this: FilterList emptyList = new FilterList((Set<Integer>)Collections.emptySet()); This also gives me an error! Ok, how about this: Set<Integer> empty = Collections.emptySet(); FilterList emptyList = new FilterList(empty); Hey, it works! But why? After all, Java doesn't have type inference, which is why you get an unchecked conversion warning if you do Set<Integer> foo = new TreeSet() instead of Set<Integer> foo = new TreeSet<Integer>(). But Set<Integer> empty = Collections.emptySet(); works without even a warning. Why is that?

    Read the article

  • Consistent HashCode() and Equals() results, but inconsistent TreeMap.containsKey() result

    - by smessing
    I have the following object Node: private class Node implements Comparable<Node>(){ private String guid(); ... public boolean equals(Node o){ return (this == o); } public int hashCode(){ return guid.hashCode(); } ... } And I use it in the following TreeMap: TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>(); Now, the tree map is used in a class called Graph to store nodes currently in the graph, along with a set of their edges (from the class Edge). My problem is when I try to execute: public containsNode(n){ for (Node x : nodes.keySet()) { System.out.println("HASH CODE: "); System.out.print(x.hashCode() == n.hashCode()); System.out.println("EQUALS: "); System.out.print(x.equals(n)); System.out.println("CONTAINS: "); System.out.print(nodes.containsKey(n)); System.out.println("N: " + n); System.out.println("X: " + x); } } I sometimes get the following: HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo Anyone have an idea as to what I'm doing wrong? I'm still new to all this, so I apologize in advance if I'm overlooking something simple (I know hashCode() doesn't really matter for TreeMap, but I figured I'd include it).

    Read the article

  • Retrieve KEYWORDS from META tag in a HTML WebPage using JAVA.

    - by kooldave98
    Hello all, I want to retrieve all the content words from a HTML WebPage and all the keywords contained in the META TAG of the same HTML webpage using Java. For example, consider this html source code: <html> <head> <meta name = "keywords" content = "deception, intricacy, treachery"> </head> <body> My very short html document. <br> It has just 2 'lines'. </body> </html> The CONTENT WORDS here are: my, very, short, html, document, it, has, just, lines Note: The punctuation and the number '2' are ruled out. The KEYWORDS here are: deception, intricacy, treachery I have created a class for this purpose called WebDoc, this is as far as I have been able to get. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Set; import java.util.TreeSet; public class WebDoc { protected URL _url; protected Set<String> _contentWords; protected Set<String> _keyWords public WebDoc(URL paramURL) { _url = paramURL; } public Set<String> getContents() throws IOException { //URL url = new URL(url); Set<String> contentWords = new TreeSet<String>(); BufferedReader in = new BufferedReader(new InputStreamReader(_url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { // Process each line. contentWords.add(RemoveTag(inputLine)); //System.out.println(RemoveTag(inputLine)); } in.close(); System.out.println(contentWords); _contentWords = contentWords; return contentWords; } public String RemoveTag(String html) { html = html.replaceAll("\\<.*?>",""); html = html.replaceAll("&",""); return html; } public Set<String> getKeywords() { //NO IDEA ! return null; } public URL getURL() { return _url; } @Override public String toString() { return null; } }

    Read the article

1 2  | Next Page >