Search Results

Search found 2563 results on 103 pages for 'collections'.

Page 11/103 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Imperative vs. LINQ Performance on WP7

    - by Bil Simser
    Jesse Liberty had a nice post presenting the concepts around imperative, LINQ and fluent programming to populate a listbox. Check out the post as it’s a great example of some foundational things every .NET programmer should know. I was more interested in what the IL code that would be generated from imperative vs. LINQ was like and what the performance numbers are and how they differ. The code at the instruction level is interesting but not surprising. The imperative example with it’s creating lists and loops weighs in at about 60 instructions. .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: .method private hidebysig instance void ImperativeMethod() cil managed 2: { 3: .maxstack 3 4: .locals init ( 5: [0] class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> someData, 6: [1] class [mscorlib]System.Collections.Generic.List`1<int32> inLoop, 7: [2] int32 n, 8: [3] class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> CS$5$0000, 9: [4] bool CS$4$0001) 10: L_0000: nop 11: L_0001: ldc.i4.1 12: L_0002: ldc.i4.s 50 13: L_0004: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) 14: L_0009: stloc.0 15: L_000a: newobj instance void [mscorlib]System.Collections.Generic.List`1<int32>::.ctor() 16: L_000f: stloc.1 17: L_0010: nop 18: L_0011: ldloc.0 19: L_0012: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator() 20: L_0017: stloc.3 21: L_0018: br.s L_003a 22: L_001a: ldloc.3 23: L_001b: callvirt instance !0 [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current() 24: L_0020: stloc.2 25: L_0021: nop 26: L_0022: ldloc.2 27: L_0023: ldc.i4.5 28: L_0024: cgt 29: L_0026: ldc.i4.0 30: L_0027: ceq 31: L_0029: stloc.s CS$4$0001 32: L_002b: ldloc.s CS$4$0001 33: L_002d: brtrue.s L_0039 34: L_002f: ldloc.1 35: L_0030: ldloc.2 36: L_0031: ldloc.2 37: L_0032: mul 38: L_0033: callvirt instance void [mscorlib]System.Collections.Generic.List`1<int32>::Add(!0) 39: L_0038: nop 40: L_0039: nop 41: L_003a: ldloc.3 42: L_003b: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() 43: L_0040: stloc.s CS$4$0001 44: L_0042: ldloc.s CS$4$0001 45: L_0044: brtrue.s L_001a 46: L_0046: leave.s L_005a 47: L_0048: ldloc.3 48: L_0049: ldnull 49: L_004a: ceq 50: L_004c: stloc.s CS$4$0001 51: L_004e: ldloc.s CS$4$0001 52: L_0050: brtrue.s L_0059 53: L_0052: ldloc.3 54: L_0053: callvirt instance void [mscorlib]System.IDisposable::Dispose() 55: L_0058: nop 56: L_0059: endfinally 57: L_005a: nop 58: L_005b: ldarg.0 59: L_005c: ldfld class [System.Windows]System.Windows.Controls.ListBox PerfTest.MainPage::LB1 60: L_0061: ldloc.1 61: L_0062: callvirt instance void [System.Windows]System.Windows.Controls.ItemsControl::set_ItemsSource(class [mscorlib]System.Collections.IEnumerable) 62: L_0067: nop 63: L_0068: ret 64: .try L_0018 to L_0048 finally handler L_0048 to L_005a 65: } 66:   67: Compare that to the IL generated for the LINQ version which has about half of the instructions and just gets the job done, no fluff. .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: .method private hidebysig instance void LINQMethod() cil managed 2: { 3: .maxstack 4 4: .locals init ( 5: [0] class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> someData, 6: [1] class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> queryResult) 7: L_0000: nop 8: L_0001: ldc.i4.1 9: L_0002: ldc.i4.s 50 10: L_0004: call class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> [System.Core]System.Linq.Enumerable::Range(int32, int32) 11: L_0009: stloc.0 12: L_000a: ldloc.0 13: L_000b: ldsfld class [System.Core]System.Func`2<int32, bool> PerfTest.MainPage::CS$<>9__CachedAnonymousMethodDelegate6 14: L_0010: brtrue.s L_0025 15: L_0012: ldnull 16: L_0013: ldftn bool PerfTest.MainPage::<LINQProgramming>b__4(int32) 17: L_0019: newobj instance void [System.Core]System.Func`2<int32, bool>::.ctor(object, native int) 18: L_001e: stsfld class [System.Core]System.Func`2<int32, bool> PerfTest.MainPage::CS$<>9__CachedAnonymousMethodDelegate6 19: L_0023: br.s L_0025 20: L_0025: ldsfld class [System.Core]System.Func`2<int32, bool> PerfTest.MainPage::CS$<>9__CachedAnonymousMethodDelegate6 21: L_002a: call class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0> [System.Core]System.Linq.Enumerable::Where<int32>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>, class [System.Core]System.Func`2<!!0, bool>) 22: L_002f: ldsfld class [System.Core]System.Func`2<int32, int32> PerfTest.MainPage::CS$<>9__CachedAnonymousMethodDelegate7 23: L_0034: brtrue.s L_0049 24: L_0036: ldnull 25: L_0037: ldftn int32 PerfTest.MainPage::<LINQProgramming>b__5(int32) 26: L_003d: newobj instance void [System.Core]System.Func`2<int32, int32>::.ctor(object, native int) 27: L_0042: stsfld class [System.Core]System.Func`2<int32, int32> PerfTest.MainPage::CS$<>9__CachedAnonymousMethodDelegate7 28: L_0047: br.s L_0049 29: L_0049: ldsfld class [System.Core]System.Func`2<int32, int32> PerfTest.MainPage::CS$<>9__CachedAnonymousMethodDelegate7 30: L_004e: call class [mscorlib]System.Collections.Generic.IEnumerable`1<!!1> [System.Core]System.Linq.Enumerable::Select<int32, int32>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>, class [System.Core]System.Func`2<!!0, !!1>) 31: L_0053: stloc.1 32: L_0054: ldarg.0 33: L_0055: ldfld class [System.Windows]System.Windows.Controls.ListBox PerfTest.MainPage::LB2 34: L_005a: ldloc.1 35: L_005b: callvirt instance void [System.Windows]System.Windows.Controls.ItemsControl::set_ItemsSource(class [mscorlib]System.Collections.IEnumerable) 36: L_0060: nop 37: L_0061: ret 38: } Again, not surprising here but a good indicator that you should consider using LINQ where possible. In fact if you have ReSharper installed you’ll see a squiggly (technical term) in the imperative code that says “Hey Dude, I can convert this to LINQ if you want to be c00L!” (or something like that, it’s the 2010 geek version of Clippy). What about the fluent version? As Jon correctly pointed out in the comments, when you compare the IL for the LINQ code and the IL for the fluent code it’s the same. LINQ and the fluent interface are just syntactical sugar so you decide what you’re most comfortable with. At the end of the day they’re both the same. Now onto the numbers. Again I expected the imperative version to be better performing than the LINQ version (before I saw the IL that was generated). Call it womanly instinct. A gut feel. Whatever. Some of the numbers are interesting though. For Jesse’s example of 50 items, the numbers were interesting. The imperative sample clocked in at 7ms while the LINQ version completed in 4. As the number of items went up, the elapsed time didn’t necessarily climb exponentially. At 500 items they were pretty much the same and the results were similar up to about 50,000 items. After that I tried 500,000 items where the gap widened but not by much (2.2 seconds for imperative, 2.3 for LINQ). It wasn’t until I tried 5,000,000 items where things were noticeable. Imperative filled the list in 20 seconds while LINQ took 8 seconds longer (although personally I wouldn’t suggest you put 5 million items in a list unless you want your users showing up at your door with torches and pitchforks). Here’s the table with the full results. Method/Items 50 500 5,000 50,000 500,000 5,000,000 Imperative 7ms 7ms 38ms 223ms 2230ms 20974ms LINQ/Fluent 4ms 6ms 41ms 240ms 2310ms 28731ms Like I said, at the end of the day it’s not a huge difference and you really don’t want your users waiting around for 30 seconds on a mobile device filling lists. In fact if Windows Phone 7 detects you’re taking more than 10 seconds to do any one thing, it considers the app hung and shuts it down. The results here are for Windows Phone 7 but frankly they're the same for desktop and web apps so feel free to apply it generally. From a programming perspective, choose what you like. Some LINQ statements can get pretty hairy so I usually fall back with my simple mind and write it imperatively. If you really want to impress your friends, write it old school then let ReSharper do the hard work for! Happy programming!

    Read the article

  • convert ArrayList.toString() back to ArrayList in one call

    - by dotnetnewbie
    I have a toString() representation of an ArrayList. Copying the toString() value to clipboard, I want to copy it back into my IDE editor, and create the ArrayList instance in one line. In fact, what I'm really doing is this: my ArrayList.toString() has data I need to setup a unit test. I want to copy this ArrayList.toString() into my editor to build a test against this edge case I don't want to parse anything by hand My input looks like this: [15.82, 15.870000000000001, 15.92, 16.32, 16.32, 16.32, 16.32, 17.05, 17.05, 17.05, 17.05, 18.29, 18.29, 19.16] The following do not work: Arrays.asList() google collections Lists.newArrayList() Suggestions?

    Read the article

  • 'Set = new HashSet' or 'HashSet = new Hashset'?

    - by Pureferret
    I'm intialising a HashSet like so in my program: Set<String> namesFilter = new HashSet<String>(); Is this functionally any different if I initilise like so? HashSet<String> namesFilter = new HashSet<String>(); I've read this about the collections interface, and I understand interfaces (well, except their use here). I've read this excerpt from Effective Java, and I've read this SO question, but I feel none the wiser. Is there a best practice in Java, and if so, why? My intuition is that it makes casting to a different type of Set easier in my first example. But then again, you'd only be casting to something that was a collection, and you could convert it by re-constructing it.

    Read the article

  • .net dictionary and lookup add / update

    - by freddy smith
    I am sick of doing blocks of code like this for various bits of code I have: if (dict.ContainsKey[key]) { dict[key] = value; } else { dict.Add(key,value); } and for lookups (i.e. key - list of value) if (lookup.ContainsKey[key]) { lookup[key].Add(value); } else { lookup.Add(new List<valuetype>); lookup[key].Add(value); } Is there another collections lib or extension method I should use to do this in one line of code no matter what the key and value types are? e.g. dict.AddOrUpdate(key,value) lookup.AddOrUpdate(key,value)

    Read the article

  • C# - Accesing to items for a collection inherited from List<string>

    - by Salvador
    I am trying to implement a new class inherited from List<string>, to load the contents from a text file to the items. using System.Collections.Generic; using System.IO; using System.Linq; public class ListExt: List<string> { string baseDirectory; public LoadFromFile(string FileName) { this._items = File.ReadAllLines(FileName).ToList();//does not work because _list is private } } but i dont knew how to load the lines into the _items property because is private. any suggestions?

    Read the article

  • What is a custom collection?

    - by Win Coder
    A Group of objects. However i am having confusion in the following case. A sample class Class A { public string; } Class A_list { public A[] list; public A_list(A[] _list) { list = new A[_list.length]; for (int i = 0; i < _list.Length; i++) { list[i] = _list[i]; } } } static void Main(String[] args) { A[] names = new A[3] { new A("some"), new A("another"), new A("one"), }; A_list just_an_object = new A_list(names); } Which of the above is a custom collection the array or the object that holds array as a field or are both custom collections.

    Read the article

  • Iterables.find and Iterators.find - instead of throwing exception, get null

    - by mjlee
    I'm using google-collections and trying to find the first element that satisfies Predicate if not, return me 'null'. Unfortunately, Iterables.find and Iterators.find throws NoSuchElementException when no element is found. Now, I am forced to do Object found = null; if ( Iterators.any( newIterator(...) , my_predicate ) { found = Iterators.find( newIterator(...), my_predicate ) } I can surround by 'try/catch' and do the same thing but for my use-cases, I am going to encounter many cases where no-element is found. Is there a simpler way of doing this?

    Read the article

  • C# dictionary and lookup add / update

    - by freddy smith
    I am sick of doing blocks of code like this for various bits of code I have: if (dict.ContainsKey[key]) { dict[key] = value; } else { dict.Add(key,value); } and for lookups (i.e. key - list of value) if (lookup.ContainsKey[key]) { lookup[key].Add(value); } else { lookup.Add(new List); lookup[key].Add(value); } Is there another collections lib or extension method I should use to do this in one line of code no matter what the key and value types are? e.g. dict.AddOrUpdate(key,value) lookup.AddOrUpdate(key,value)

    Read the article

  • Shortcut for adding to List in a HashMap

    - by Damo
    I often have a need to take a list of objects and group them into a Map based on a value contained in the object. Eg. take a list of Users and group by Country. My code for this usually looks like: Map<String, List<User>> usersByCountry = new HashMap<String, List<User>>(); for(User user : listOfUsers) { if(usersByCountry.containsKey(user.getCountry())) { //Add to existing list usersByCountry.get(user.getCountry()).add(user); } else { //Create new list List<User> users = new ArrayList<User>(1); users.add(user); usersByCountry.put(user.getCountry(), users); } } However I can't help thinking that this is awkward and some guru has a better approach. The closest I can see so far is the MultiMap from Google Collections. Are there any standard approaches? Thanks!

    Read the article

  • How can I create a collection of references in C#

    - by Jonathan Kaufman
    Ok I am having a cross language hiccup. In C# with it's great collections like List and I have: a Map class with properties of: List<byte[]> Images; List<Tile> Tiles; a Tile Class of: byte[] ImageData; int X; int Y; Now I want to add an image to the Map class and have the ImageData property of the Tile Classes to "reference" it. I have discovered I can't just assign it Images[0]. You can't have a reference to an object of a List. My fix was to create a Dictionary. Is this the best way or can I somehow have a "pointer" to a collection of objects?

    Read the article

  • C# - implementing GetEnumerator() for a collection inherited from List<string>

    - by Vojtech
    Hi, I am trying to implement FilePathCollection. Its items would be simple file names (without a path - such as "image.jpg"). Once the collection is used via foreach cycle, it should return the full path created by concatenating with "baseDirectory". How can I do that? public class FilePathCollection : List<string> { string baseDirectory; public FileCollection(string baseDirectory) { this.baseDirectory = baseDirectory; } new public System.Collections.IEnumerator GetEnumerator() { foreach (string value in this._list) //this does not work because _list is private yield return baseDirectory + value; } } Thanks in advance! :-)

    Read the article

  • Subtracting two lists in Python

    - by wich
    In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0] and b = [0, 1, 1] I'd like to do something like c = a - b and have c be [2, 0] or [0, 2] order doesn't matter to me. This should throw an exception if a does not contain all elements in b. Note this is different from sets! I'm not interested in finding the difference of the sets of elements in a and b, I'm interested in the difference between the actual collections of elements in a and b. I can probably work this out with a for loop, looking up the first element of b in a and then removing the element from b and from a, etc. But this doesn't appeal to me, I'd like to do this with list comprehension in a nice and easy way. Is this possible?

    Read the article

  • Is there a good collection library for C-language?

    - by matti
    We have to maintain and even develop C-code of our legacy system. Is there good collection library that would support Java/C# (new versions) style collections. Hashtable, HashSet, etc. Of course without objects, but with structs. The HashTable key limitations to "strings" and ints is not a problem. It wouldn't be bad if it's free even for commercial use. I'm back to C from C# and I must say i'm depressed using our own libraries and the language in general. We're using VS2005 and MS C-compiler if that has nothing to do with anything. Thanks & BR -Matti

    Read the article

  • Java List Sorting: Is there a way to keep a list permantly sorted automatically like TreeMap?

    - by david
    In Java you can build up an ArrayList with items and then call: Collections.sort(list, comparator); Is there anyway to pass in the Comparator at the time of List creation like you can do with TreeMap? The goal is to be able add an element to the list and instead of having it automatically appended to the end of the list, the list would keep itself sorted based on the Comparator and insert the new element at the index determined by the Comparator. So basically the list might have to re-sort upon every new element added. Is there anyway to achieve this in this way with the Comparator or by some other similar means? Thanks.

    Read the article

  • Using Custom Generic Collection faster with objects than List

    - by Kaminari
    I'm iterating through a List<> to find a matching element. The problem is that object has only 2 significant values, Name and Link (both strings), but has some other values which I don't want to compare. I'm thinking about using something like HashSet (which is exactly what I'm searching for -- fast) from .NET 3.5 but target framework has to be 2.0. There is something called Power Collections here: http://powercollections.codeplex.com/, should I use that? But maybe there is other way? If not, can you suggest me a suitable custom collection?

    Read the article

  • 2 compareTo method overriden in the same class definition, how could I force to use the second?

    - by jayjaypg22
    I want to sort a list List<Blabla> donnees by a criterion on one of its field. My problem is that compareTo is already overriden for this Class. So I've got something like : Blabla { public int compareTo(Object other) { ... } public int compareTo(Blabla other) { ... } } In a business layer class I call : Business { method (){ Collections.sort(List<Blabla > donnees); } } But this call N°1 compareTo method with object parameter. How could I sort my list with the N°2 method?

    Read the article

  • C#, Using Custom Generic Collection faster with objects than List

    - by Kaminari
    Hello, I'm using for now List< to iterate through some object collection and find matching element, The problem is that object has only 2 significant values Name and Link (strings) but has some other values wich I dont want to compare. I'm thinkig about using something like HashSet (wich is exactly what I'm searching for - fast) from .NET 3.5 but target framework has to be 2.0. There is something called Power Collections here: http://powercollections.codeplex.com/ But maybe there is other way? If not, can you suggest me a suitable custom collection?

    Read the article

  • Is map/collection order stable between calls?

    - by John
    If I have a hash map and iterate over the objects repeatedly, is it correct that I'm not guaranteed the same order for every call? For example, could the following print two lines that differ from each other: Map<String,Integer> map = new HashMap<String,Integer>() {{ put("a", 1); put("b", 2); put("c", 3); }}; System.out.println(map); System.out.println(map); And is this the case for sets and collections in general? If so, what's the best way in case you have to iterate twice over the same collection in the same order (regardless of what order that is)? I guess converting to a list.

    Read the article

  • Output of Iterable.sliding as Tuple

    - by ziggystar
    The method sliding on collections returns a sliding window of given size in the form of X[Iterable[A]] with X being the type of the collection and A the element type. Often I need two or three elements and I prefer to have them named. One ugly workaround for sliding(2) is the following: points.sliding(2).foreach{ twoPoints => val (p1,p2) = (twoPoints.head,twoPoints.last) //do something } This sucks and only works for two elements. Also note that (a,b) = (twoPoints(0),twoPoints(1)) doesn't work. Help me!

    Read the article

  • Why would you use a MyObject[] internally, but expose a List<MyObject>?

    - by timmyd
    I have come across a class that has an immutable property: MyObject[] allObjs The property is initialized like this: List<MyObject> objs = createAllMyObjects(); allObjs = objs.toArray(new MyObject[objs.size()]); When it is exposed through the accessor, it's done as a List: public List<MyObject> getAllMyObjects() { return Collections.unmodifiableList(Arrays.asList(allObjs)); } Why would a programmer do this? Is there a benefit that I don't know about? Performance is not a concern, as the array of objs will only ever number in a few dozen elements. It seems that we are going round and round in circles. The class is a sort of factory, so it's got a private constructor and exposes only static methods (not sure if this could be a reason for the madness).

    Read the article

  • Oracle E-Business Financials Recommended Patch Collections (RPCs) for R12.1.3 Have Been Released for August 2012

    - by Oracle_EBS
    What is a Recommended Patch Collection (RPC)? An RPC is a collection of recommended patches consolidated into a single, downloadable patch, ready to be applied. The RPCs are created with the following goals in mind: Stability: Address issues that occur often and interfere with the normal completion of crucial business processes, such as period close--as observed by Oracle Development and Global Customer Support. Root Cause Fixes: Deliver a root cause fix for data corruption issues that delay period close, normal transaction flow actions, performance, and other issues. Compact: While bundling a large number of important corrections, we have kept the file footprint as small as possible to facilitate uptake and minimize testing. Reliable: Reliable code with multiple customer downloads and comprehensive testing by QA, Support and Proactive Support. RPCs are available for the following products: Cash Management Collections E-Business Tax Financials for India Fixed Assets General Ledger Internet Expenses iReceivables Loans Payables Payments Receivables Subledger Accounting For the latest Financials Recommended Patch Collections (RPCs), please view: EBS: R12.1 Oracle Financials Recommended Patches [Doc ID 954704.1].

    Read the article

  • Sorting in Hash Maps in Java

    - by Crystal
    I'm trying to get familiar with Collections. I have a String which is my key, email address, and a Person object (firstName, lastName, telephone, email). I read in the Java collections chapter on Sun's webpages that if you had a HashMap and wanted it sorted, you could use a TreeMap. How does this sort work? Is it based on the compareTo() method you have in your Person class? I overrode the compareTo() method in my Person class to sort by lastName. But it isn't working properly and was wondering if I have the right idea or not. getSortedListByLastName at the bottom of this code is where I try to convert to a TreeMap. Also, if this is the correct way to do it, or one of the correct ways to do it, how do I then sort by firstName since my compareTo() is comparing by lastName. import java.util.*; public class OrganizeThis { /** Add a person to the organizer @param p A person object */ public void add(Person p) { staff.put(p.getEmail(), p); //System.out.println("Person " + p + "added"); } /** * Remove a Person from the organizer. * * @param email The email of the person to be removed. */ public void remove(String email) { staff.remove(email); } /** * Remove all contacts from the organizer. * */ public void empty() { staff.clear(); } /** * Find the person stored in the organizer with the email address. * Note, each person will have a unique email address. * * @param email The person email address you are looking for. * */ public Person findByEmail(String email) { Person aPerson = staff.get(email); return aPerson; } /** * Find all persons stored in the organizer with the same last name. * Note, there can be multiple persons with the same last name. * * @param lastName The last name of the persons your are looking for. * */ public Person[] find(String lastName) { ArrayList<Person> names = new ArrayList<Person>(); for (Person s : staff.values()) { if (s.getLastName() == lastName) { names.add(s); } } // Convert ArrayList back to Array Person nameArray[] = new Person[names.size()]; names.toArray(nameArray); return nameArray; } /** * Return all the contact from the orgnizer in * an array sorted by last name. * * @return An array of Person objects. * */ public Person[] getSortedListByLastName() { Map<String, Person> sorted = new TreeMap<String, Person>(staff); ArrayList<Person> sortedArrayList = new ArrayList<Person>(); for (Person s: sorted.values()) { sortedArrayList.add(s); } Person sortedArray[] = new Person[sortedArrayList.size()]; sortedArrayList.toArray(sortedArray); return sortedArray; } private Map<String, Person> staff = new HashMap<String, Person>(); public static void main(String[] args) { OrganizeThis testObj = new OrganizeThis(); Person person1 = new Person("J", "W", "111-222-3333", "[email protected]"); Person person2 = new Person("K", "W", "345-678-9999", "[email protected]"); Person person3 = new Person("Phoebe", "Wang", "322-111-3333", "[email protected]"); Person person4 = new Person("Nermal", "Johnson", "322-342-5555", "[email protected]"); Person person5 = new Person("Apple", "Banana", "123-456-1111", "[email protected]"); testObj.add(person1); testObj.add(person2); testObj.add(person3); testObj.add(person4); testObj.add(person5); System.out.println(testObj.findByEmail("[email protected]")); System.out.println("------------" + '\n'); Person a[] = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("------------" + '\n'); a = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("SORTED" + '\n'); a = testObj.getSortedListByLastName(); for (Person b : a) { System.out.println(b); } } } Person class: public class Person implements Comparable { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int compareTo(Object o) { String s1 = this.lastName + this.firstName; String s2 = ((Person) o).lastName + ((Person) o).firstName; return s1.compareTo(s2); } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return this.email.toLowerCase().hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } }

    Read the article

  • Sorting and Re-arranging List of HashMaps

    - by HonorGod
    I have a List which is straight forward representation of a database table. I am trying to sort and apply some magic after the data is loaded into List of HashMaps. In my case this is the only hard and fast way of doing it becoz I have a rules engine that actually updates the values in the HashMap after several computations. Here is a sample data representation of the HashMap (List of HashMap) - {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=21, toDate=Tue Mar 23 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=456} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=20, toDate=Thu Apr 01 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 24 10:54:12 EDT 2010, eventId=22, toDate=Sat Mar 27 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Fri Mar 26 10:54:12 EDT 2010, actionId=1234} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 31 10:54:12 EDT 2010, actionId=1234} {fromDate=Mon Mar 15 10:54:12 EDT 2010, eventId=12, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=567} I am trying to achieve couple of things - 1) Sort the list by actionId and eventId after which the data would look like - {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=456} {fromDate=Mon Mar 15 10:54:12 EDT 2010, eventId=12, toDate=Wed Mar 17 10:54:12 EDT 2010, actionId=567} {fromDate=Wed Mar 24 10:54:12 EDT 2010, eventId=22, toDate=Sat Mar 27 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=21, toDate=Tue Mar 23 10:54:12 EDT 2010, actionId=1234} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=20, toDate=Thu Apr 01 10:54:12 EDT 2010, actionId=1234} {fromDate=Wed Mar 17 10:54:12 EDT 2010, eventId=11, toDate=Fri Mar 26 10:54:12 EDT 2010, actionId=1234} {fromDate=Sat Mar 20 10:54:12 EDT 2010, eventId=11, toDate=Wed Mar 31 10:54:12 EDT 2010, actionId=1234} 2) If we group the above list by actionId they would be resolved into 3 groups - actionId=1234, actionId=567 and actionId=456. Now here is my question - For each group having the same eventId, I need to update the records so that they have wider fromDate to toDate. Meaning, if you consider the last two rows they have same actionId = 1234 and same eventId = 11. Now we can to pick the least fromDate from those 2 records which is Wed Mar 17 10:54:12 and farther toDate which is Wed Mar 31 10:54:12 and update those 2 record's fromDate and toDate to Wed Mar 17 10:54:12 and Wed Mar 31 10:54:12 respectively. Any ideas? PS: I already have some pseudo code to start with. import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.commons.lang.builder.CompareToBuilder; public class Tester { boolean ascending = true ; boolean sortInstrumentIdAsc = true ; boolean sortEventTypeIdAsc = true ; public static void main(String args[]) { Tester tester = new Tester() ; tester.printValues() ; } public void printValues () { List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>() ; HashMap<String,Object> map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(21)) ; map.put("fromDate", getDate(1) ) ; map.put("toDate", getDate(7) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(456)) ; map.put("eventId", new Integer(11)) ; map.put("fromDate", getDate(1)) ; map.put("toDate", getDate(1) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(20)) ; map.put("fromDate", getDate(4) ) ; map.put("toDate", getDate(16) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(22)) ; map.put("fromDate",getDate(8) ) ; map.put("toDate", getDate(11)) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(11)) ; map.put("fromDate",getDate(1) ) ; map.put("toDate", getDate(10) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(1234)) ; map.put("eventId", new Integer(11)) ; map.put("fromDate",getDate(4) ) ; map.put("toDate", getDate(15) ) ; list.add(map); map = new HashMap<String,Object>(); map.put("actionId", new Integer(567)) ; map.put("eventId", new Integer(12)) ; map.put("fromDate", getDate(-1) ) ; map.put("toDate",getDate(1)) ; list.add(map); System.out.println("\n Before Sorting \n "); for(int j = 0 ; j < list.size() ; j ++ ) System.out.println(list.get(j)); Collections.sort ( list , new HashMapComparator2 () ) ; System.out.println("\n After Sorting \n "); for(int j = 0 ; j < list.size() ; j ++ ) System.out.println(list.get(j)); } public static Date getDate(int days) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, days); return cal.getTime() ; } public class HashMapComparator2 implements Comparator { public int compare ( Object object1 , Object object2 ) { if ( ascending == true ) { return new CompareToBuilder() .append(( ( HashMap ) object1 ).get ( "actionId" ), ( ( HashMap ) object2 ).get ( "actionId" )) .append(( ( HashMap ) object2 ).get ( "eventId" ), ( ( HashMap ) object1 ).get ( "eventId" )) .toComparison(); } else { return new CompareToBuilder() .append(( ( HashMap ) object2 ).get ( "actionId" ), ( ( HashMap ) object1 ).get ( "actionId" )) .append(( ( HashMap ) object2 ).get ( "eventId" ), ( ( HashMap ) object1 ).get ( "eventId" )) .toComparison(); } } } }

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >