FAQ Database Discussion Community


getting a value from a map in java with index

java,collections
The item shown below is the result obtained from debugging a map {0={PRODUCT_TYPE.PRODUCT_AMT=200}} To store this value in a string I have used this code String amountCheck=(String) productsFieldMap.get("PRODUCT_TYPE.PRODUCT_AMT"); However this does not seems to work. Can anyone suggest me a way to do this? The productsFieldMap represents the map where...

Keep (minim) object in a collection by two attribute keys in java

java,collections,set,comparator,treeset
For example I have a list that contains 3 objects: List<Student> studentList= new ArrayList<Student>(); list.add(new Student("name1", 5); list.add(new Student("name3", 6); list.add(new Student("name1", 7); class Student{ String name; Integer grade;} My filtering logic: if name is equal then i need to filter out the objects that have maximum grade - so...

Java collection interface that guarantees no duplicates as well as preservation of insertion order

java,collections
Is there a java collection interface that guarantees no duplicates as well as the preservation of insertion order at the same time? This is exactly what LinkedHashSet is doing? However, I am wondering if there is also an interface guaranteeing the same thing in order to avoid direct dependency on...

How replace one list items with another in java?

java,arraylist,collections
I have two array lists, Can it possible to replace the one list items with the second list. ArrayList<String> a = new ArrayList<String>(); ArrayList<String> b = new ArrayList<String>(); a.add("testone"); a.add("testtwo"); a.add("testthree"); b.add("demoone"); b.add("demotwo"); System.out.println("List values are: "+ a); Is there any way to replace the first list with the second...

Merge two or more T in List based on condition

c#,linq,collections
I have the below class: public class FactoryOrder { public string Text { get; set; } public int OrderNo { get; set; } } and collection holding the list of FactoryOrders List<FactoryOrder>() here is the sample data FactoryOrder("Apple",20) FactoryOrder("Orange",21) FactoryOrder("WaterMelon",42) FactoryOrder("JackFruit",51) FactoryOrder("Grapes",71) FactoryOrder("mango",72) FactoryOrder("Cherry",73) My requirement is to merge the...

Async GetMany method in Repository

c#,asynchronous,collections
I have repository method which returns collection according to filter public IEnumerable<T> GetMany(Expression<Func<T, bool>> filter = null) { IQueryable<T> query = DbSet; if (filter != null) { query = query.Where(filter); } return query.ToList(); } Now i want to write this method as Async. And this is my problem. Should i...

“Comparison method violates its general contract!”, everything seems OK

java,collections,compare,comparator,comparable
I am aware of the compare rules in Java (and in general) as described here. I have an ArrayList of Strings. Each String represent a Texas Hold'em Poker Hand ignoring the suit. Each String is exactly 13 characters long. Each String consists of digits only whose sum is 7. For...

Meteor collection - count same values

mongodb,collections,meteor,spacebars
I need to count all products in descending order and display them with spacebars. How would I do that? Result should be: book : 2 tv : 1 // My Collection Records = new Mongo.Collection('records'); // My database Records.insert({ name: "a", product: "book" }); Records.insert({ name: "b", product: "tv" });...

LEFT OUTER JOIN of two collections

java,collections
The question is pretty much in the title. I'm looking for an algorithm more efficient than full search through the collections. I have two collections: List<Map<TypeId, Object> > col1; List<Entity> col2; Where public enum TypeId{ PLAYER, PARTNER, PLATFORM, AMOUNT } and public class Entity{ private int player_id; private int platform_id...

Update multiple values in an oracle table using values from an APEX collection

sql,oracle,collections,apex
I am using APEX collections to store some values and pass them between pages in Oracle Application Express 4.2.3. I would like to then perform an update statement on a table called "project" with the values from the collection. My code so far is as follows: update project SET name=c.c002,...

Collections.sort isn't sorting

java,sorting,java-ee,collections
I am building a web application using Java EE (although my problem is more Java based) In a Servlet, I am getting a list of orders from the EJB. In this list of orders, there is a list of states for this order (sent, on dock, non received ...) I...

How to Map a Ternary Map of Dates With a Bidirectional Relationship?

java,database,hibernate,collections,orm
I've read: JPA: How to map a Map with Date as key but I have the opposite of the question, I have the value component of the Map as a Date. How should I map this? Map: Map<Club, java.util.Date> Can you show an example including the code for the Club...

VBA values of collection into Excel using VBA

excel,vba,excel-vba,dictionary,collections
I am trying to copy values into an Excel sheet using VBA code. I have been trying to use a dictionary (as using in my function (8) and utilized in section (3) and (4) ). When I had it set as a dictionary, everything was off by one so I...

Delete single model from collection in Backbone.View

javascript,backbone.js,collections,model
var PlayersView = Backbone.View.extend({ collection: players, //collection of players el: "#playersList", //I bind to the class render: function () { this.$el.html(""); for (var i=0; i<this.collection.size(); i++) { var player = this.collection.at(i); this.$el.append("<li "+"value='"+player.get("id")+"'>"+player.get("names")[0]+" "+player.get("surnames")[0]+" <a href='#' class='edit'>[edit]</a>"+"</li>"); } //what I render is in the picture below return this; }, events:...

Is it possible to add a collection of strings directly into the Sitecore Content Editor?

string,collections,sitecore7,sitecore-editor
here's a really quick question... Is there a type of Sitecore Editor control that I can use in the Template Builder to enable the product owners to add a free collection of strings in the CMS Editor? I know that I can add a simple data object that has a...

how does hashmap ensure that each hash value is assigned a unique index in the hash table

java,collections,hashmap
I want to understand how hash() and indexOf() methods of HashMap assign a unique index in hash table to a hashmap. In other words, why it is not possible for multiple hash values to be mapped to the same index.

Entity Framework, Code First, Update independent association (Collection)

c#,entity-framework,collections,ef-code-first
to explain the problem I have a simple model with a class Person: public class Person { public int Id { get; set; } public virtual string Name { get; set; } } and a class School with a collection of Persons: public class School { public int Id {...

Why does the Java.Util.Stack not pop last element in the loop?

java,collections,stack
I have a very Basic Question Stack<Integer> s=new Stack<integer>(); s.push(New Integer(1)); s.push(New Integer(2)); s.push(New Integer(3)); for(int i=0;i<s.size();i++){ System.out.println("i: "+i+" size:"+s.size()); System.out.print(s.pop()); if(s.size()>=1) System.out.print(" ->"); } This results in an output of 3->2-> And Not 3->2->1 Shouldn't the loop run thrice , Is the condition i < s.size() changing as the...

Meteor Collection Says It's Empty

javascript,database,mongodb,collections,meteor
I posted this (Shared Collection Between Client and Server Meteor) earlier, and I'm not sure it's completely solved but I believe another problem has arisen. When doing console.log(Streams.find().fetch()); in my client.js file, the result is []. But when I use meteor mongo to check the database (db.Streams.find().forEach(printjson)), three different objects...

How does Collections.binarySearch work?

java,collections
I am trying to understand how Collections.binarySearch work in Java. I don't quite understand the output I get. public static void main(String args[]) { // create arraylist ArrayList<String> arlst=new ArrayList<String> (); arlst.add("A"); arlst.add("D"); arlst.add("C"); arlst.add("B"); arlst.add("E"); int index=Collections.binarySearch(arlst, "D", Collections.reverseOrder()); System.out.println(index); } } The output of this code is -1....

Search for key in Map when the values are in ArrayList [closed]

java,arraylist,collections,hashmap,key-value
I am new to the collections in Java , I have a HashMap<String, List<String>>. I want to search for a key from the Map when a value is given. The map stores the data of a state as key and its cities as the list. So it is assumed that...

Should remove(Object) be remove(? super E)

java,generics,collections,super,contravariance
In this answer, I tried to explain why the Collection method add has the signature add(E) while remove is remove(Object). I came up with the idea that the correct signature should be public boolean remove(? super E element) And since this is invalid syntax in Java, they had to stick...

Merge multiple lists based on List priority

java,sorting,collections,priority
I have couple of lists where each list has different priority. When i merge these lists i should get with height priority on top. Assume i have 3 lists and different objects value common in 3 lists should come first and then the top priority list should be appended vice...

Reflection , java , iterate on collection

java,reflection,collections
I'm writing a function that will iterate on some collection , I don't know what collection I'm getting , so I wrote this till now , the PrintFieldsOfClass will get some object or collection of objects and I will have to print the fields of the class , I have...

Java Generic Map with Generic Type as key/ values

java,generics,collections
I want to write a method which takes a Map as an parameter, which can contain any object as its value. I am trying to implement it using generics, but I am unable to implement it. Below is the code that I have tried so far. This code as two...

PLSQL move data from csv list stored in varchar2 to a collection of integers

sql,oracle,collections,plsql
Oracle Express 11G R2: In PLSQL I have a varchar2 containing a CSV list of values like this: vList:='1212,3232,3232,4343,54545,65654,65665,65654,788787' I would like to move these into a collection, so i create a new type: CREATE TYPE INTEGER_TT AS TABLE OF INTEGER; then declare my variable: my_list INTEGER_TT; What is the...

I can't use in GWT Collections.unmodifiableList(List l) to make only readable my List, because isn't serializable, alternative ways?

java,list,collections,gwt-rpc,unmodifiable
I'm using GWT-RPC to create an application. At certain point the server return a Collection using Collections.unmodifiableList(List l) to the client. The client give an error: [WARN] Exception while dispatching incoming RPC call com.google.gwt.user.client.rpc.SerializationException: Type 'java.util.Collections$UnmodifiableList' was not included in the set of types which can be serialized by this...

Java Collection Sort: Issue while sorting list

java,sorting,collections
This question has been asked many times what i understood is it should return 0 as well with 1 and -1 but still I am getting this exception java.lang.IllegalArgumentException: Comparison method violates its general contract! at java.util.TimSort.mergeHi(TimSort.java:895) at java.util.TimSort.mergeAt(TimSort.java:512) at java.util.TimSort.mergeForceCollapse(TimSort.java:453) at java.util.TimSort.sort(TimSort.java:250) at java.util.Arrays.sort(Arrays.java:1512) at java.util.ArrayList.sort(ArrayList.java:1454) at...

Java generic usage error

java,collections,java-generics
The code below uses simple generics and compiles correctly. When I try to create a object of type McDelayQueue, I get an error. public class McDelayQueue<E extends Delayed & IValue<K>, K> extends DelayQueue<E> { final Set keys = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>()); @Override public E take() throws InterruptedException { E data...

Why object of number can be added in TreeSet

java,collections,wrapper,comparable
The object of class which we want to add into TreeSet, that Class must implement Comparable interface But Number class does not implement Comparable then how TreeSet allow Number to get added. Number n1= 11; Number n2= 12; Number n3= 13; Set<Number> set = new TreeSet<>(); set.add(n1); set.add(n2); set.add(n3); ...

Ensure List of elements ordered by field in element

collections,java-8,guava,method-reference
Using Guava it is possible to ensure ascending ordering this way: import com.google.common.collect.Ordering; import io.predictor.dao.ohlcv.OhlcvHm; import static java.util.stream.Collectors.toList; assertThat("Ordered by age", Ordering.natural().isOrdered( employees.stream().map(Employee::getAge).collect(toList()))); It is strange for me that Guava (for all its close relation to Java lambdas) does not provide easy solution for such cases. Of course I can...

List items order

.net,collections
Does the generic List guarantee the order of its items when adding and iterating the values? If so, is it in the definition of the type or is it just an assumption on the usual behavior? Updated: It looks like the order is kept for now; there is no trace...

VBA Debugger shows only 256 elements of a collection

excel-vba,debugging,collections
the title explains my problem. Im working on an excelmakro and my questions is, is there an option that the debugger shows all elements like it does with an array? And if not, is the only workaround the storage of my classobjects in an array after inflating the collection? I...

Couchbase Bulk loading error with upsert() (.NET SDK 2.0)

c#,.net,collections,couchbase,upsert
I have encountering an error when inserting bulk data with the upsert function and cannot figure out how to fix it. Anyone know what is wrong here? What the program is essentially doing is grabbing data from a SQL server database and loading into our Couchbase bucket on an Amazon...

Is there a way to bind a couple of instances to many different keys in Guice?

java,collections,guava,guice
We need to create some mapping between many types of some object, described with enum values: public enum ObjectType { Type1,Type2,Type3,Type4,Type5...TypeN } ... and several instances of strategies to use for these types or, for example, boolean values which relate to the mentioned ObjectTypes A MapBinder from Guice can be...

List.Remove(T item) removing item from original List

c#,.net,collections
I have the following code foreach (var d in dots) { var _tempPointList = new List<Point>(); _tempPointList = _pointList; foreach (var point in _tempPointList) { if (d >= point.X && d <= point.Y) { _tempPointList.Remove(point); } } } so when the integer d is between X and Y of the...

Iterate/enumerate over part of a list?

c#,collections,enumeration
Is there a way to remember the position of an enumerator? I want to remember the position of an enumerate, so that I can reset it to a position before the current. I don't want to go back to the beginning so .reset() doesn't help. Btw, is it possible to...

complex collection in java

java,collections
I need to define a collection of user defined objects with the following access methods: access by the object's primary key (unique) access by index of the collection sorted on a secondary key (not unique) Each object has a primary key and a secondary key (not guaranteed unique). When an...

Returning an Iterator from String[] [duplicate]

java,arrays,collections
This question already has an answer here: Iterator of Object[] 2 answers I have a class foo with a field String[] bar. I want foo to implement Iterable<String>. So I'm writing @Override public Iterator<String> iterator() { // ToDo - return some function of `bar` } What can I put...

Shopfy accessing all products from a collection on the product page

collections,shopify,product,liquid
I'm using Shopify as my eCommerce platform. My customer has some products that are related to each other. But don't think of a typical related products system, basically these products have parts, and those individual parts can be reordered separate from the product itself. The client wants to list all...

Is there a Java class that lets me iterate trough the last x elements? [duplicate]

java,list,collections,iterator
This question already has an answer here: How to start iterating through ArrayList from set index? [closed] 5 answers I am looking for something like a LinkedList with a function that returns an iterator for the last x elements. For example: LinkedList<Oky> obj; obj.add(a); obj.add(b); obj.add(c, d, e, f,...

Groovy List : Group By element's count and find highest frequency elements

collections,groovy
I have a groovy list as below def certs = ['0xc1','0xc1','0xc1','0xc1','0xc2','0xc2','0xc3','0xc4','0xc4','0xc5','0xc5','0xc5','0xc5'] Am trying to find the occurance of each element and group by its count. I've tried certs.groupBy { it }.findAll { it.value.size() } but am getting the below output [0xc1:[0xc1, 0xc1, 0xc1, 0xc1], 0xc2:[0xc2, 0xc2], 0xc3:[0xc3], 0xc4:[0xc4, 0xc4], 0xc5:[0xc5,...

Collection without duplicates (based on id) but keeps the highest version number

java,collections,duplicates
This seems like something that should have a standard solution, but I can't find what I'm looking for. It's not difficult to implement by hand, but perhaps I'm just missing a tool in my toolbox? In pseudo-code, I want a set-like collection that, given existing entries {id_1, v_1}, {id_2, v_2}...

Finding the desired amount of smallest Doubles in an ArrayList

java,arraylist,collections
I have an ArrayList filled with Double values, and based on user input (an int), I need to find the indices of the entered amount of smallest Doubles from this List. For example, if the user were to type in 5, and the ArrayList looked as such (is actually much...

Loop by Object inside another Object in Java

java,list,oop,collections
I'm not sure how to ask this in word so here's an example : Building class have a data like this : Map<Season, List<Info>> infosBySeason = new TreeMap<Season, List<Info>>(); What I'd like to do is loop for each Building, print by Season infos. Like : Season 1 : Building 1...

VBA Class : Collection.item member is a collection . How to retrieve sub collection item elements

vba,class,collections
I have this template data Header of file ((string1, string2...) group1 header (string1, string2...) group1/line1 (string1, string2...) group1/line2 (string1, string2...) group2 header (string1, string2...) group2/line1 (string1, string2...) group2/line2 (string1, string2...) Note : The datas belonging to group header and group line are different type even if they are on the...

Performance of element-compare in java collections

java,performance,collections
Problem: Given two Collection<?>s, check if both contain the same elements. Assuming that the actual implementation of the collection is unknown Assuming that the elements do not occur in the same order Assuming that no element does occur twice in the same collection Solution 1: boolean equals = c1.containsAll(c2) &&...

Difference between converting List to Array

java,arrays,list,collections
I was just wondering what is the difference between following two approach of converting List to Array. List<String> test = new ArrayList<String>(); test.add("AB"); test.add("BC"); test.add("CD"); test.add("DE"); test.add("EF"); String[] testarray = test.toArray(new String[0]); // passing 0 as Array size And below one : List<String> test = new ArrayList<String>(); test.add("AB"); test.add("BC"); test.add("CD");...

Continuously add digits to a string

string,c#-4.0,collections,selenium-webdriver,iteration
Just a quick one, I want to continuously add digits to a string. The first thing I did is to remove the last character of the string, now digits starting from 1 should be continuously added to it. The snippet is below: using System; using System.Collections.Generic; namespace ConsoleApplication3 { class...

Backbone checkbox value in tr view

jquery,table,backbone.js,checkbox,collections
I'm currently programming the web interface for a mvc web application and I need to get the models which have their checkbox checked. At the moment this is the template i use to generate a single table row: <td><span class="userintern"><%= intern %></span></td> <td><span class="username"><%= name %></span></td> <td><input id="add" class="add" type="checkbox"...

Do I really need to implement iterator in that case?

java,collections,iterator
I need some advice about usage of Iterable<T> in Java. I have the following class: public abstract class Validator implements Comparable<Validator>{ public abstract boolean validate(); public abstract int getPriority(); @Override public int compareTo(Validator o) { return getPriority() > o.getPriority() ? -1 : getPriority() == o.getPriority() ? 0 : 1; }...

function: why are all children updating in this backbone collection?

javascript,backbone.js,collections
I have a Backbone collectionView that holds x amount of companies. I also have a collection of x amount of products. I want to get a random product and add it to a list of "assets" on a random company. (the company is returned from the this.getRandomCompany() function) But when...

Fill immutable map with for loop upon creation

scala,dictionary,collections,initialization,immutability
I have this map that looks like this: val fields: Map[(Int, Int), Field] and I thought about doing something like: val fields: Map[(Int, Int), Field] = Map( for(a <- 0 to 10) { (0, a) -> new Field(this, 0, a) } ) instead of a long copy/paste list like: (0,...

How to find the index of the Object(that has its own parameters) in arraylist with using indexOf method

java,arraylist,collections,indexof
I have the ArrayList of the objects Song. Each Song has its own parameters, title, composer, duration,. I'm trying to write the method that will be looking for the title of the object Song and will give me the INDEX of the object in ArrayList with this parameter. songs is...

How to compare lists of objects with 3 or more variables(fields) in Java

java,list,collections,compare
I have 3 fields for defining a unique object, e.g.: region, name, platform which are string values. A list of such objects has to be compared with another list of such objects. I was thinking to create an object for that such as Class myObject{ private String region; private String...

UnmodifiableMap with Function values fails to compile

java,function,collections,unmodifiable
I have a reference: public final static LinkedHashMap<String, Function<OrderBean, String>> DELEGATES; Which I initialize like: static { LinkedHashMap<String, Function<OrderBean, String>> tmp = new LinkedHashMap<>(); tmp.put(OrderCols.FIELD1, OrderBean::getFIELD1); tmp.put(OrderCols.FIELD2, OrderBean::getFIELD2); ... DELEGATES = Collections.unmodifiableMap(tmp); } On the last line of the static block (the assignment to DELEGATES), I get this compiler error:...

Collections.sort comparison method violates its general contract

java,sorting,collections,comparator
First of all, sorry for asking a question to this topic again. I'm well aware that there are plenty of questions and answers here. I've read some of them but my problem is that I still cannot figure out what I'm doing wrong. Here is my code: Collections.sort(hLines, new Comparator<Line>()...

Quick & Easy: why won't this run?

java,arrays,parsing,netbeans,collections
//markParse is an Integer ArrayList //ii is the number of elements in markParse //analysis is a textArea in the program's design int max = java.util.Collections.max(markParse); int min = java.util.Collections.min(markParse); int range = max - min; int average = sumData/ii; analysis.setText("Avg: " + average); analysis.append("Max: " + max); analysis.append("Min: " +...

Decorate each item resolved in a collection with Castle Windsor

collections,castle-windsor,decorator
Suppose I have an interface with multiple base implementations: interface IPrinter { void Print(); } class Printer1 : IPrinter { public void Print() { Console.WriteLine(GetType()); } } class Printer2 : IPrinter { public void Print() { Console.WriteLine(GetType()); } } I also have a decorator implementation: class ModifyingPrinter : IPrinter {...

why java API prevents us to call add and remove together?

java,list,collections,listiterator
As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

joining two collections in C# or JavaScript

javascript,c#,linq,collections
I have two objects of "pseudotype" Hash(int key, list values) that I need to combine into one based on the key. For example, [{1, {a, b, c}}, {2, {apple, pear}}, {3, {blue, red}}] and [{2, {tomato}}, {3, {pink, red}}, {4, {x, y, z}}] The result that I need is: [{1,...

Why does AbstractCollection implement both Iterable and Collection?

java,collections,interface
AbstractCollection implements both the Iterable and Collection interfaces. However, Collection is a subinterface of Iterable. Would it not suffice just to have AbstractCollection implement Collection?

Mapping a list to Map Java 8 stream and groupingBy

java,collections,lambda,java-8
I have this simple Bean class: public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } In...

Searching multiple radio button collections in hta

loops,collections,vbscript,hta
Bellow is a hta/vbs code I wrote to dynamically build a form with radio buttons. The hta is launched by another vbs script that specifies the amount of radio button (yes/no) collections to create. The issue I'm having is in the Sub Write in the loop While x <= ItemListSize....

Hibernate: Remove Item From Collection Without Initialazing

hibernate,collections,many-to-many
I'm having troubles with an Hibernate Many To Many Collection. When i try to remove an item from the relation, hibernate loads the entire collection (is too big). Here is an example: supose A has many to many relation with B public class A { @ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST,...

Get those elements from a List of custom class objects whose one property value is parseable to double

c#,.net,linq,list,collections
I have a list of custom class objects in C# with class structure like this: public class ABC { int ID; string Text1; string Text2; } This list stores data like this: +-----+-------+--------+ | ID | Text1 | Text2 | +----------------------+ | 1 | PQR | test1 | | |...

Using counter on array for one value while keeping index of other values

python,collections
After reading the answers on this question How to count the frequency of the elements in a list? I was wondering how to count the frequency of something, and at the same time retreive some extra information, through something like an index. For example a = ['fruit','Item#001'] b = ['fruit','Item#002']...

What sorting algorithm used while overriding compare method of comparator interface?

java,algorithm,sorting,collections
Collections.sort(ar, new Comparator<Intervals>() { @Override public int compare(Intervals o1, Intervals o2) { return (Integer.valueOf(o1.getEnd())) .compareTo(Integer.valueOf(o2.getEnd())); } }); Hi all, I have the above code in java. Here, ar is a list and Intervals is a class with 2 integer variables : Start and End. I wanted to know what...

add subitems to meteor document

mongodb,meteor,collections,insert-update
I have a meteor collection "list" that has the following data structure. "list" : [ { "_id" : "id", "author" : "authorId", "createdOn" : "DateTime", "description" : "description", "items" : [ { "item1" : { "itemComplete" : "Boolean", "itemName" : "item name", "itemDescription" : "item description", } }, { "item2"...

Objectify: Filter by an attribute of collection entries?

google-app-engine,collections,objectify
I'm using Objectify on Google's AppEngine. I have the following Entity-Model: @Entity public class ChallengeEntity { @Id private Long id; @Index public List<ChallengeParticipant> participants; } The Participant (not an entity... should it be one?) public class ChallengeParticipant { @Load public Ref<UserEntity> user; // ... participant-specific attributes } And the User-Entity:...

ActiveAdmin formtastic link_to on a collection leading to the show view

ruby-on-rails-4,collections,activeadmin,formtastic,link-to
Just wondering about how to have this link to this to the appropriate supplier_company_view with clickable names. The .to_sentence is optional. column :supply_companies do |pt| pt.supply_companies.collect {|c| c.company_name.capitalize }.to_sentence end ...

Add to list mvc

asp.net-mvc,list,razor,collections
I'm trying to add string data to list, but have null reference exception and don't have any idea how to fix this. Here home controller: public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(ChatUser model) { if (ModelState.IsValid) { **model.chatGroup.Add(model.inputGroups);** - here excepton } return View(model); } And...

cogroup two RDD in scala

java,scala,collections,apache-spark,iterable
I am trying to cogroup two RDDs in my function for some calculations. My code is below: def myCogroupFunction(teachers: org.apache.spark.rdd.RDD[Teacher], students: org.apache.spark.rdd.RDD[Student]) { val teacherPairs = teachers.map { t => val nameKey: String = t.getName() (nameKey.toUpperCase(), t) } val studentPairs = students.map { s => val nameKey: String = s.getName()...

Converting collection to array with no extra memory

java,arrays,performance,memory,collections
I need to convert Map into 2D array, so I've wrote this piece of code but it eats a lot of memory and I can't figure out why. private DataItem[][] convertDataToArrays(boolean[] filter, Map<Integer, List<T>> dataSet) double[] data = new double[sizeOfNewVector]; DataItem[][] reducedData = new DataItem[dataSet.size()][]; for (int i = dataSet.size()...

How to convert single element list to java 8 optional

java,collections,java-8,optional
How to nicely convert list containing one or zero elements to Optional? The ugly code: List<Integer> integers = new ArrayList<>(); Optional<Integer> optional = integers.size() == 0 ? Optional.empty() : Optional.of(integers.get(0)); ...

LoDash - DeepFlatten array of objects

javascript,collections,lodash,flatten
I have the following collection. Each object may have a children array of objects, which may have a children array of objects and so on... [ { "name": "John", "age": 24, "children": [ { "name": "Jack", "age": 53, "children": [ { "name": "Jenny", "age": 88 } ] } ] },...

MongoDB check for Collection before creating it

php,mongodb,collections
I am creating an install script, but I want to make sure that the collections that I am installing are not already being used by another program. I am wondering is there a PHP function that returns 0 or 1 if the collection exists in the database? I know I...

How i can get list from some class properties with java 8 stream

java,collections,java-8,java-stream
Good day. I have a list of Person. I need get a list from property of Person. For example i have a Person class: class Person{ private String name; private String birthDate; public String getName(){ return name; } public String getBirthDate(){ return birthDate; } Person(String name){ this.name = name; }...

What is the best way to iterate two hashmap in same loop in java?

java,data-structures,collections
What's the best way to iterate over the below two maps together? I want to compare two maps values which are strings and have to get the keys and values. HashMap<String, String> map1; HashMap<String, String> map2; ...

I am trying to remove a single value from a MultiMap(org.apache.commons.collections.MultiMap) in JAVA

java,collections,graph,hashmap
I am trying to remove a single value from a MultiMap (org.apache.commons.collections.MultiMap) in Java. The issue is it contains two values. When I remove one, the other gets removed as well. class MappedValue { public MappedValue(String id , boolean touched) { identifier = id; this.touched=touched; } private String identifier; private...

Shortest way to extract Map from List in Java

java,collections,java-7,guava
I have a List List<FeatureHolder> featureHolderList; consisting of FeatureHolder objects public class FeatureHolder { private String flag; private String value; } Now I need to extract Map from the featureSetList. The solution is, of course, trivial: Map<String, String> map = new HashMap<>(); for(FeatureHolder fh: featureHolderList){ map.put(fh.getFlag(), fh.getValue()); } The question...

how to keep 10 biggest integer while reading a list in java?

java,sorting,collections
I have a list of integer in a list and want to keep the 10 biggest while I'm iterating over the list and keep them in a TreeSet. I'm using this code : for(Integer i : list) { if (treeSet.size() < 10) { treeSet.add(i); } else if (i > treeSet.last())...

ArrayList cannot be converted to string.

java,arraylist,collections
Okay, I'm making a CD collection Program and everything was going well as I followed along my lesson but then I ran into the problem of wanting to make it show up in the jTextArea. I bet there is a simple solution but I cannot find one. I'm new to...

Properly defining collection in java

java,arrays,collections
While reading collections in java and browsing some of the questions on stackoverflow, I came across this question: Method for adding Objects into a fixed collection(Array) in Java Here an Array has been referred to as fixed collection. Conceptually, is it legitimate to call an Array a 'fixed collection' or...

Backbone.js collection fetch not setting response objects as models

backbone.js,collections,fetch
When fetching a collection, my api response has 10 objects, but the resulting Backbone collection only has 1 model with an attributes array containing the 10 response objects....to put it another way, the fetch is not creating models out of the objects in my response...and I don't know why. Model...

Shared Collection Between Client and Server Meteor

javascript,mongodb,collections,meteor,client
Beginner at Meteor. Just learning how everything works so bear with me. Everything was working fine in one file, but after installing iron:router to have a multi-page application, I realized that it's better to have separate client and server files. Unfortunately, now I'm having trouble syncing the collection between the...

Iterating through a list searching for duplicates

java,list,collections,iterator
So I have this task that I must do a dice roller and then search for a certain combination if it was rolled. I have an overriden equals method, that checks for the combination and it is working properly. Every object from the class Dice has its own string array...

“Class.Property” is not accessible in this context because it is 'Private'

vb.net,loops,collections
I'm looking access private member of a class in myproject.vb file. My function header in myproject.vb looks like this, Public Function MyVbFunction(ByVal objRequest As BookRequest) As Integer Try For Each book As Book In objRequest.m_Books If Myvbfucntion2(book) = 1 Then Return True End If Next End Try End Function Book...

Iterator for an array list of Class

java,collections,iterator,listiterator
Am New to Java so please bear with me if my question seems to be silly. I am learning collections,I have written a program which will store student names id and marks.I am storing all these in a Arraylist. Using for loop I am able to print the values in...

Creating the array in which every element has couple of parameters

java,generics,arraylist,collections
I need to create the array/arraylist (don't know what is better in this situation) in which every element of the array will have 3 parameters. it must be an array of songs(elements) and each song must have these 3 parameters(title, name, duration). later I will need to count all the...

Java - Create sublist from a list based on suffix

java,arraylist,collections,iterator,sublist
I'm trying to create sublists from a list based on the suffix. public class Test { public static void main(String args[]) { List<List<String>> subList = new ArrayList<List<String>>(); List<String> myList = new ArrayList<String>(); myList.add("Text_1"); myList.add("XYZ_3"); myList.add("ABC_1"); myList.add("Text_2"); myList.add("Text_3"); myList.add("XYZ_1"); myList.add("XYZ_2"); myList.add("ABC_2"); for (String item : myList) { List<String> tempList = new...

Why doesn't my sample throw ConcurrentModificationException [duplicate]

java,collections,concurrentmodification
This question already has an answer here: Why isn't this code causing a ConcurrentModificationException? 4 answers I wrote this example following a test ConcurrentModificationException concept: public class Person { String name; public Person(String name) { this.name = name; } } public static void main(String[] args) { List<Person> l =...

Where can I find the definitions of System.Collections.Concurrent classes in the mono source code?

c#,collections,mono
I am looking for the source code of the System.Collections.Concurrent classes, especially ConcurrentQueue and ConcurrentDictionary in the mono sources. I am unable to find them. I was looking in the corlib Directory: https://github.com/mono/mono/tree/master/mcs/class/corlib but it does not contain the System.Collections.Concurrent package. Even using the repository search feature of github did...

“Segmentize” collection with lodash

javascript,collections,lodash
I have a collection col1 var col1 = [1, 8, 9, 10, 2, 54, 7]; I have another collection col2 var col2 = [1, 8, 23, 9, 46, 10, 2, 54, 78, 7] ...that I know it contains every element of col1, plus some other elements I want to...

Time complexity of LinkedList, HashMap, TreeSet? [closed]

java,collections,time-complexity
I am a student of CS, learning about Java Collections. At my school we have received a chart with with time complexity of different operations on data structures. There are some things in the chart that don't make sense to me. Linked List It says that time complexity for inserting...

Comparing if two list of strings are equal using hashcode?

java,java-ee,collections,jax-rs
I am writing a Java/JEE client server application. I have a requirement were the files present in the server should match with the files present in the client. I am only trying to validating if there is an exact match to the file names and number of files in a...

Java random shuffle list with two elements using Collections.shuffle

java,random,collections
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; public class ShuffleList { public static void main(String[] args) { String [] file = {"1","2"}; long seed = 3; ArrayList<String> fileList = new ArrayList<String>(Arrays.asList(file)); for (int i=0; i<200; i++) { Collections.shuffle(fileList, new Random(seed)); seed = seed +1; System.out.println(seed + "," + fileList);...

Offset and limit for a set

java,algorithm,collections
I have two ordered sets of Integers - SortedSet<Integer>, call them set1 and set2. I need to find a union of that sets and return the subset offset 10 limit 10. What do I mean? Set1: 1,2,5,6,7,8,11,21,23,543,1002 Set2: 11,12,15,16,17,8,111,121,123,1543,11002 Union: 1,2,5,6,7,8,11,21,23,543,1002,12,15,16,17,111,121,123,1543,11002 Union offset 10 limit 10: 1002,12,15,16,17,111,121,123,1543,11002 Note, that cardinalities...

Meteor, '/users/insert' is already defined

javascript,facebook,mongodb,meteor,collections
I'm creating basic Administration Panel and I didn't work with MongoDB yet. For development purposes I left autopublish and insecure in the project. In order to render users from database (Accounts-ui + Accounts-facebook) i need a handler for Users = new Mongo.Collection("users"); but during compilation there is following error: '/users/insert'...

dividing the text files in block

java,collections
I am trying to read a text file and divide it into blocks. Below is the pattern of input text file: DEFINE JOBSET ID=jobset_def FAILCOND=(1,9999) DEFINE JOB ID=(jobset_def,job1_def,0010) DESCRIPTION='Checks the data file against the token file' DEFINE JOBPARM ID=(jobset_def,job1_def,0010) SUBFILE=/scripts/chk_file.ksh SUBUSER=pbods SUBPASS=*PASSWORD* PARM1='parm1' PARM2='parm2.dat' DEFINE JOB ID=(jobset_def,job2_def,0030) DEFINE JOBPARM ID=(jobset_def,job2_def,0030)...