Questions tagged [collections]

1

votes
2

answer
51

Views

Storing user input in array not starting from 0

My problem is that in my code below, in OPTION 2, if the user Store = 1 and the item details overwrites the item[0] with the new details. I want it to store in item[7] and not to overwrite the current information. The Item is found in constructor method in another class. Please see how i can fix thi...
Rohan
1

votes
1

answer
555

Views

Adding object to a Collection in the first position with backbone?

I have this simple function to add a Folder to a collection called 'Folders'. folderAdded: function(folder) { this.folders.add(folder); this.$el.empty(); this.render(); } By default this will add the object in the first position, so it will appear the first one. As my query is order by created, if I...
Duveral
1

votes
1

answer
2.1k

Views

Adding elements to a list in a for loop

var locations: List[Location] = List[Location]() for (x
Cyan
1

votes
1

answer
527

Views

UnsupportedOperationException When Inserting into Map

I am using the Spark's collectAsMap function [Spark CollectAsMap to obtain a Map. In this map, when I do the put operation I am getting the following exception: ERROR ApplicationMaster: User class threw exception: java.lang.UnsupportedOperationException java.lang.UnsupportedOperationException at jav...
Sanchay
1

votes
1

answer
48

Views

PECS For generics in Non Collections

Joshua Bloch came up with the PECS, which says the rule when to use ? extends T and ? super T. If you think about PECS in terms of Collections framework, then it is very straightforward. If you add values to the data structure, use ? super T. If you read from the data structure, use ? extends T. fo...
Fatih Arslan
3

votes
4

answer
70

Views

Add values from basic array to Set<String>

I have this: private Set fields = new HashSet(); public void fields(String... s){ this.fields.addAll(s); } but that doesn't compile, it says: addAll (java.util.Collection
rakim
2

votes
2

answer
19

Views

Map collection using stream is yielding strange compilation error

I have this method: public void fields(TableField... s){ // compilation error on next line Collection fields = Arrays.asList(s).stream().map(v -> v.getValue()); this.fields.addAll(fields); } and TableField is simple just looks like: class TableField { public String getKey() { return this.key; } publ...
MrCholo
11

votes
4

answer
103

Views

Collecting a collection of list based on similar index

I have a collection like : List firstList I want to group together a similar list of pattern : List secondList but grouped by indexes. say firstList [1]: 0 = {Object A}" 1 = {Object B}" 2 = {Object C}" firstList [2]: 0 = {Object A}" 1 = {Object B}" 2 = {Object C}" I want to group this collection...
Einstein_AB
1

votes
2

answer
1.6k

Views

Concurrent Modification Exception in Java Set

As a part of my program I stuck to Concurrent Modification Exception. Here is the mentioned part: PriorityQueue marginalGainHeap = new PriorityQueue( 1, new Comparator() { public int compare(Customer c1, Customer c2) { return Double.compare(c1.getMarginalGain(), c2.getMarginalGain()); } }); // set o...
Ali n
3

votes
1

answer
47

Views

How to implement and fire an event when a change occurs in a property of `T` in `List<T>` within the owning class

How to implement and fire an event when a change occurs in a property of T in List within the owning class I mean, not on the collection itself but in a property of T. Is there any pattern how to do it? My current code public class Section { public string Title { get; set; } public List Questions {...
0

votes
0

answer
7

Views

Problem while updating a child list in C # ASP.Net MVC

public class PayRateDaysModel. { public string day_name { get; set; } public List multiplier { get; set; } } public class RateList { public double start_after { get; set; } public double rate_multiplier { get; set; } } when I'm trying to update any value in multiplier of PayRateDaysModel then its...
kritikaTalwar
3

votes
3

answer
75

Views

Scala - Collection comparison - Why is Set(1) == ListSet(1)?

Why is the output of this comparison outputs true? import scala.collection.immutable.ListSet Set(1) == ListSet(1) // Expect false //Output res0: Boolean = true And in a more general sense, how the comparison is actually done?
Aaron_ab
1

votes
3

answer
77

Views

Object references in HashMap

How do the below code provides value of the Employee object e2 as employee even I didn't add e2 to the HashMap. I would like to know how e2 is referred here. import java.util.HashMap; public class Employee { int phno; String name; public static void main(String[] args) { // TODO Auto-generated meth...
niks
1

votes
3

answer
533

Views

Combining two lists of objects into one based on a business logic with Scala

In continuation of Scala learning curve I have two lists of objects. I need to merge these lists into one list, while applying a logic with matching pares. So, for example, here are the two lists: case class test(int: Int, str: String) val obj1 = test(1, "one") val obj2 = test(2, "two") val list1 =...
Shurik Agulyansky
1

votes
1

answer
154

Views

How to use Java 8 features to generate collection? [duplicate]

This question already has an answer here: How can I turn a List of Lists into a List in Java 8? 6 answers If I have a class Book that has inside it a List of Page objects, how can I generate a collection of objects of Page given a collection of Book objects, using Java 8 features such as Streams, C...
ITWorker
0

votes
3

answer
74

Views

Convert a String into a set<Character> using a Stream java 8

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz"; SortedSet set= new TreeSet(); for (int i = 0; i < ALPHABET.length(); i++) { set.add(new Character(ALPHABET.charAt(i))); } I would like to convert this for loop in Java 8 way. It could be better if using a stream. Output will be the...
Harsh
1

votes
1

answer
2.4k

Views

What is the difference between Collection and Set interfaces in Java?

The declared method signatures seem to be equal. So what is the purpose of introducing Set interface rather then implementing Collection directly? Or is it just sort of a marker interface here?
Roman
1

votes
1

answer
118

Views

java.util.ConcurrentModificationException Can someone explain me the logical reason for this

i am creating a class call student and want to store those on the list i am using iterator to fetch the elements from list but i cant do so because an exception is happening and i cant resolve the exception which is happening here,it would be great help if someone can give me the logical reason for...
Avishka Perera
1

votes
5

answer
1.6k

Views

Write a program to find length of longest consecutive sequence in array of integers?

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. public class Array { public static void main(String args[]){ int a[]={10,15,1,2,3,4,5,11,12}; int b=1; int c=0; for(int i=0;i=c) { System.out.println(a[i]); } else{ b=0; } } } } } But i am getting...
Sainath Pawar
1

votes
1

answer
1.3k

Views

C# awaitable collection

Is there a standard way to await for a collection to be marked as complete by another task (thread?) I am looking for something like await collection.Completion.Task So far I found the following approaches: Use a TaskCompletionSource variable (needs to be shared with the other task/thread) Use a Bl...
phaedo
1

votes
3

answer
776

Views

Check if value exists in List<List<objects>> in java?

I want to check if an objects exists in the List and return the index of List if the object is found. Eg: List listOfLists = new ArrayList(); List listOne = new ArrayList(); listOne.add(1); listOne.add(9); listOfLists.add(listOne); List listTwo = new ArrayList(); listTwo.add(5); listTwo.add(7); lis...
Nobody
-1

votes
0

answer
17

Views

The proper way to change a value in a Map to the corresponding value in another map where the first value is the key

First of all sorry for the long question, but I was wondering if somebody could help me do this in a proper elegant way. public void fillInfo(List elements) { Map fixClass = new Controls().getClassmap(); if(elements.contains("Primary")){ //form elements has a field that has as value "Primary" or "Se...
PhilipBSS
0

votes
0

answer
7

Views

Spring- How to remove a property from a list of Objects?

I have an Entity "Person" which has following properties, Id Name F-Name Age Address When I call a repository function findAll() on Person, it returns a list of Persons. List list = somefuntionToConvertIterableToList(personRepository.findAll()); this list has multiple objects of Person Type. Person...
1

votes
1

answer
262

Views

Insert row into Oracle type table of object

I am able to BULK COLLECT queries into tables of type object but cannot seem to do a simple insert. Must I use a BULK collect even on a single row insert? DROP TYPE T_TABLE; / CREATE OR REPLACE TYPE T_ROW AS OBJECT ( ID NUMBER(10), DESCRIPTION VARCHAR2(50) ); / CREATE OR REPLACE TYPE T_TABLE AS...
Kurt
2

votes
7

answer
67

Views

How to return the entire list if filter is false

I have this list List lstStr = new ArrayList(); lstStr.add("1"); lstStr.add("2"); lstStr.add("3"); lstStr.add("4"); lstStr.add("5"); When I search for the string "1" its should return a List = ["1"] and if search string is not in the list for example "0" it should return the entire List =["1","2","...
alvagenesis
1

votes
2

answer
141

Views

Adding single quotes to a string in Scala

we are trying to add single quotes to each element of a set of string's in Scala val s : Set[String] = Set("abcd","cdef") Expected outcome is val s : Set[String] = Set("'abcd'","'cdef'") tried multiple approaches Approach1: s.map(x => x.mkString("'", "', '", "'")) Approach2: s.map(x => '\'' + x + '...
user2359997
1

votes
1

answer
58

Views

Which element has been added to the ArrayList as last?

For example: I have an ArrayList composed of Points. Every point have an array of ints which defines his position. I can have few points in this same position and add them to my ArrayList at every index I want. The question is: I have given position and I want to check if any point of my ArrayList...
Szymon Żak
1

votes
4

answer
137

Views

How to check String contains one of Strings in collection

I want to check if the target string contains string in collections. And match the longest one. E.g. Target string: str = "eignelaiwgn" Collection strings: eig, a, eb, eigne, eignep The result needs to be eigne First I thought HashMap, but it is not sorted. So I try to put collection strings into A...
Bejond
1

votes
1

answer
57

Views

Understanding scanRight in Scala

I am having trouble understanding the following implementation of the scanRight function in Scala. def scanRight[B](z: B)(f: (A, => B) => B): Stream[B] = foldRight((z, Stream(z)))((a, p0) => { lazy val p1 = p0 val b2 = f(a, p1._1) (b2, cons(b2, p1._2)) })._2 A typical application of scanRight would...
clog14
1

votes
1

answer
42

Views

Time Complexity - Copying Map Entries to Arraylist

I was looking for efficient ways to sort a hashmap by it's value and I came across solutions that claim to be O(n log n) by copying the entries to a List and sorting the List by values; copy back into a LinkedHashMap. I was thinking this may be O(n^2) instead of O(n log n). List entries = new ArrayL...
Venkatesh
0

votes
0

answer
13

Views

Update the properties of a list

I have created a list with several properties, among these properties, I have a property heightMin and property heightMax. What I want to do is when modifying one of the properties (heightMin or heightMax), this triggers the update on the other properties (heightMin and heightMax) of the list. HtMin...
Axel
0

votes
0

answer
4

Views

Fast 2D integral coordinate to custom class dictionary collection in C#

I need a fast collection that maps 2D int-typed point to custom class in C#. The collection needs to have: Fast lookup (coords to custom class), adding a point if it does not exist Fast remove range of key-point (outside of given rect). This actually rules out Dictionary, as profiling found out this...
PiotrK
1

votes
2

answer
58

Views

Accessing scala immutable Set

as I go along with scala I stumbled upon a code which I fully do not understand its internals. Would be great if some more experienced developer put some shed on that. Code snippet looks pretty simple: var cache = Set.empty[String] ... if (!cache(url) && depth > 0) ... cache += url question here i...
jaksky
23

votes
7

answer
670

Views

How to get a List<E> from a HashMap<String,List<E>>

I want to extract a List from a Map (E is a random Class) using stream(). I want a simple one-line method using java 8's stream. What I have tried until now : HashMap map = new HashMap(); List list = map.values(); // does not compile list = map.values().stream().collect(Collectors.toList()); // doe...
12

votes
9

answer
602

Views

Reversing a Queue<Integer> and converting it into an int array

I have a Queue declared as Queue queue=new LinkedList();, I need to reverse the elments order in it, and then convert it into an int array. I wrote below code: Collections.reverse((List)queue); int[] res=queue.stream().mapToInt(Integer::intValue).toArray(); This code has two problems: the explict c...
ZhaoGang
1

votes
4

answer
518

Views

java infinite loop while using collections [closed]

Please suggest me to solve the below infinite loop . Class object contains the collection of same type objects. While converting to String , The object calls the toString of each object in the collection. Hence it leads to infinite loop. Please dont use any static variables. import java.util.LinkedL...
ranganath111
1

votes
1

answer
181

Views

Collection changing variable type, using Access & VBA

I am using a Collection to store the variable of Type SubForm but when I go to retrieve the object, it is of type Controls. Can someone tell me why this is? For Each ctl In Me.controls Select Case ctl.ControlType Case acSubform Debug.Print "subform: " & TypeName(ctl) If (ctl.Name = "a" Or ctl.Name =...
Nate
1

votes
3

answer
86

Views

What would be an appropriate collection type for storing few elements?

Of the different collection types supported in Scala (lists, maps, hashmaps, set etc) what would be an appropriate collection type for implementing something that can be done by C code below typedef enum { GOOD BAD MAX_QUALITY } quality struct student_data s_data[MAX_QUALITY]; The collection size is...
Girish
1

votes
2

answer
517

Views

Sorting a List of Mixed Data?

I had an interview today and in that i was asked to sort an list which contains String and Integers.it was like this Input: car bus 4 -5 apple 3 -1 Output: apple bus -5 -1 car 3 4 I was stuck at first as i never saw anything like that but what i tried to do is that to create 2 sub-list,One which hol...
Viking
1

votes
3

answer
153

Views

Read List<custom class> Containing Single Record

I have a list which has a single record i.e which matches to a particular ID. Now I want to use this list's property(i.e. a column for that single record) without using FOREACH loop as it will just cause burden for server because my program is already having lot of loops... Can it be done?? I am fil...
Rahul Ranjan

View additional questions