Iterating Over Collections In Java 8
Aug 24, 2014
Today I installed jdk1.8.0_20 on my computer and typed a simple example code in MyEclipse 6.0 IDE, the code listed below:
import java.util.List;
public class Test5
{
public static void main(String[] args)
{
List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));
}
}
the MyEclipse Editor shows some errors like "Arrays can not be resolved" and "n can not be resolved".
I did use jdk 8 in the build path, but it seems like the jdk 8 did not function properly.
View Replies
ADVERTISEMENT
Jul 2, 2014
I am new in Collection, as per my knowledge I have already override the hashCode() and Equals() method in Data class, but when I trying to search the element it is giving "not found". find the bug.
import java.util.*;
public class WordCounter {
public static void main(String args[])
{
HashSet<Data> set=new HashSet<Data>();
set.add(new Data("this",2));
[code]....
View Replies
View Related
Mar 11, 2015
I am trying to generate table rows from LinkedHashmap sent from servlet. But whenever i execute i get empty or null map. I tried running the servlet alone to check whether the data is existing in linkedhashmap and it does. But only when i pass it to the jsp page i guess i am receiving an empty map.
Below is the code
Jsp Code:
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
[code]....
View Replies
View Related
Apr 27, 2014
Write a Java function Sum2List that takes two lists L1 and L2 of the same size and returns list L that contains the sum of data inside the corresponding nodes of lists L1 and L2.
ex: L1 = {1,2,3}
L2 = {4,5,6}
L = {5,7,9}
I do not know how to iterate through two different lists >>
public LinkedList Sum2List(LinkedList l1, LinkedList l2){
LinkedList l3 = new LinkedList();
ListNode Current1 = L1.getFront();
ListNode Current2 = L2.getFront();
while(Current1 != null){
l3.Add(Current1.getItem() + Current2.getItem());
[Code] .....
This my attempt to write the code , but the dr. side that we have not to use the build in methods ( getNext()...etc)
in the function .
View Replies
View Related
Jul 2, 2014
I have a a hashmap in request attribute which is available to jsp file where i have a dropdown. Hashmap kay= value of this dropdown. As and when I select CLT i want to perform some opertation depending on value associated with that key in hashmap.
View Replies
View Related
Apr 23, 2014
I currently have the code set up to iterate through objects and keep track of them but how do I do the same and draw the objects on the panel window? I'm confused on what to do and how to start it.
Here's the code I have so far, the 'Car' which I want to draw extends to another class which extends to GameObject. I currently have a 'draw()' method under the 'Car' class but nothing in the 'draw()' method yet. From what I understand i'm suppose to have a 'draw()' method under 'GameObjects' class also?
public class MapView extends JPanel implements IObserver, ActionListener{
JPanel myPanel;
private Timer timer = new Timer(5, this);
int x = 0;
int moveX = 2;
public MapView(){
super.setBorder(BorderFactory.createTitledBorder("Map:"));
[code]....
Mostly I don't understand how to go through the iterator again to paint the objects. Wouldn't I need to put another iterator under 'paintComponent()' or can it be done under 'update()' ?
how to get some shapes from the GameObjects onto my panel.
View Replies
View Related
Apr 18, 2015
my code is ignoring the checkbox option when Iterating in loop like this:
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td><input type="checkbox" name="deleteFromList" value="${user.id}"/><input type="submit" value="Delete" name="action" ></td>
</tr>
</c:forEach>
</tbody>
The output of value="${user.id}" is retrieved from a DB, it looks like this:
Id Nombre usuario Email Fecha de registro Acción
1 isaac2 @2 1986-01-01 *Delete(input) *Here there is check box
2 isaac3 @3 1988-01-01 *Delete(input) *Here there is check box
Then depending of which check box I selected then the row by the side should be selected by id and deleted.But what happens is that doesnt matter which check box I select, always the first row is deleted. I understand that at the first iteration of the loop it just take the first id, it doest attach the id I have choosen to the row it belongs to
View Replies
View Related
May 20, 2015
I have to create a method to find the current month with the input being a number of milliseconds using System.currentTimeMillis(). Now I was able to solve the problem with the following extremely cumbersome method:
public static int monthLeap(long ms) {
int result = 0;
int jan = 31, mar = 31, may = 31, jul = 31, aug = 31, oct = 31, dec = 31;
int apr = 30, jun = 30, sep = 30, nov = 30;
int feb = 28;
int febLeap = 29;
[Code] ....
I first go through a loop that goes through all the years and subtracting the number of days of a normal year or a leap year in milliseconds from the total milliseconds. At the end I should have a rest value of milliseconds that represents the amount of milliseconds that have passed already this year. Out of this number I then find the month we are currently in.
My problem is that the above method is way to large and I get a checkstyle warning: "NPath Complexity is 12,288 (max allowed is 80)".
I know that this can somehow be solved with a for loop iterating through the time and counting up months until there is no more month left. My problem though is the different lengths of the months. If each month was the same I could just subtract the amount of days in each month from the rest value.
(Since I already got it down to <= 12 months, I shouldnt bother with the extra days to find the month. Yet if I want to find the month when the date is the first or last day of the month it is important to be very precise) ....
View Replies
View Related
Apr 23, 2014
I am just not sure of some theory in collections, ArrayList and LinkedList maximum capacity depends on the memory allocated to the JVM. But according to few people those list has a maximum capacity of Integer.MAX_VALUE.
According to my experiment, those list has a maximum capacity of Integer.MAX_VALUE since the get method of List accept a parameter of int primitive type (index of element), therefore we can conclude that the maximum capacity of List is equal to Integer.MAX_VALUE.
But what about the Map? get() method of map accepts object(the key of the map). So does it mean that the maximum capacity of Map depends on the memory allocated to our JVM? Or its maximum size is Integer.MAX_VALUE also just like Lists and Arrays? Is there a way to prove it? Is Map designed to hold infinite number of data (disregarding the heap memory space exception)?
And also about Stack, Deque? is it also the same as Map (in terms of maximum capacity)?
View Replies
View Related
Feb 24, 2014
The Iteratior provides the functionality of traversing and removal which we can achieve through normal for loop and remove() of the data structure.Then, why do we need Iterator explicitly and as an inner class?
View Replies
View Related
Jan 22, 2014
I am using this image as a reference to learn the Collection interface better and it seems I must be getting confused with the 'ordered/unordered' types. I thought ordered would mean ordering the objects automatically like a TreeSet using the comparable interface so it could be numerically or alphabetically ordered etc..
Java Code:
public static void main(String[] args) {
Set hashSet = new HashSet();
hashSet.add(1);
hashSet.add(3);
hashSet.add(2);
for (Object o : hashSet){
System.out.print(o + " "); // Prints: 1,2,3 (Unordered but puts the numbers in order....)
[code]...
View Replies
View Related
Oct 30, 2014
When I run my code, I get an error with this line
if(Collections.binsearch(dict, word3) != -1) {
I imported the collections utility and everything. Tell me if you need to see more of the code. The exact error is binsearch is undefined for the type Collections.
View Replies
View Related
Aug 29, 2014
I have a method that draws a polygon on the screen:
public void poly(List<Point> points) {
//code
}
For the usage of the method, it makes no difference whether points is an array or a List. In fact, switching doesn't even change any of the code in the method since I use a for-each loop. So, my question is, is it a better practice to use a List as an argument, or an array when the method itself doesn't care about which to use?
View Replies
View Related
Apr 6, 2014
I have searched on internet but did not find something useful. I do not want to use collections. here's what i have written
class ArrayDemo3
{
static void union(int x[], int y[])
{
System.out.println("Union Elements:");
for(int i=0; i<x.length; i++)
{
for(int j=0; j<y.length; j++)
[code]....
View Replies
View Related
Jul 14, 2014
I am confused with the following function signature in the class java.util.Collections.
static <T> boolean replaceAll(List<T> l, T oldValue, T newValue);
I got the other parts but i could not figure out at all what is the meaning of <T> in the beginning.
View Replies
View Related
Jun 28, 2014
I am trying to create a java program to sort an array in ascending and descending order. Here is the program I created :
import java.util.Arrays;
import java.util.Collections;
public class ArraySort
{
public static void main(String [] args) {
int [] num = {5,9,1,65,7,8,9};
Arrays.sort(num);
[Code]...
BUT I GET THE FOLLOWING EROOR ON COMPILATION
ArraySort.java:12: error: no suitable method found for reverseOrder(int[])
Arrays.sort(num,Collections.reverseOrder(num));
^
method Collections.<T#1>reverseOrder(Comparator<T#1>) is not applicable
[Code] .....
What's wrong with my program?
View Replies
View Related
May 11, 2012
I'm doubted regarding the implementation of Collections.binarySearch() method on an ArrayList of objects of a custom class Movie.
Here is the movie class :
public class Movie implements Comparable<Movie> {
String movieName;
String rating;
String director;
String theme;
[Code] .....
The sort/binarySearch in searchByMovieName function is done with natural sorting (and Comparable Interface in Movie class). I mean no comparators involved here. And the comparator that I used for sorting/binarySearching on Movies Director attribute in searchByMovieDirector function is :
public class MovieDirectorComparator implements Comparator<Movie> {
public int compare(Movie movie1, Movie movie2) {
return movie1.getDirector().compareToIgnoreCase(movie2.getDirector());
}
}
But I was not able to implement binarySearch ?? How to implement the binarySearch here. I have google to see only binarySearch working on Arrays or probably ArrayList of String only, but not on ArrayList of custom objects.
View Replies
View Related
Jan 10, 2014
My friends and me are trying to make online Test taking system. We got a very basic doubt.
We have developed classes and relationship between classes for example : Online Test Taking system will have admin and student class. And Admin will have list of students.. etc.
But question troubled me was: if we use database to store all data for example student details then I can perform all sorts of operations writing sql query and store result in some other database then what is the need of "ArrayList<Student> field in Admin".??
Question is: We can put everything in database and manipulate using database(sql) functions to manipulate it.Then what is the need of Arraylist of anything which is just used to store object details for example student details....??
View Replies
View Related
Apr 22, 2015
I have a list of 100,000 + names and I need to append to that list another 100,000 names. Each name must be unique. Currently I iterate through the entire list to be sure the name does not exist. As you can imagine this is very slow. I am new to Java and I am maintaining a 15+ year old product. Is there a better way to check for an existing name?
View Replies
View Related
Jul 5, 2014
Suppose i have given a List<Intervals> list; I am iterating over list and inserting each element from list into BST, if time require to insert into BST is logn then what is the total time require to insert all the elements into tree ?
logn or nlogn ?
View Replies
View Related
Sep 12, 2014
I have tried running the java application without adding the site to site list in java security tab. But I get a sand box message as APPLICATION BLOCKED BY SECURITY SETTINGS. How to run the java application without adding the site to site list in java security tab.
View Replies
View Related
Oct 24, 2014
I want to develop a Java program that uses OpenScript APIs to test my applications. The OpenScript framework automatically creates the Java Code so I was thinking of either using this code or create my own using the APIs.
I tried both options using NetBeans but I'm getting errors everywhere starting with the library import. I'm pretty new to Java so I'm sure I'm missing a lot of things here. I pasted the code below from the OpenScript framework that want to use in a stand-alone file for your reference.,
import oracle.oats.scripting.modules.basic.api.*;
import oracle.oats.scripting.modules.browser.api.*;
import oracle.oats.scripting.modules.functionalTest.api.*;
import oracle.oats.scripting.modules.utilities.api.*;
import oracle.oats.scripting.modules.utilities.api.sql.*;
[Code] ....
View Replies
View Related
Apr 9, 2015
I've written a java application with several classes all in the same .java file. It works just fine. Now, I've broken it up so that each class has its own .java file. Still works fine. My next step is to put those classes into a package, but I'm not about to get the program to run.The .java source files are all in /home/user/src
I've set the CLASSPATH to /home/user/src..All of the source files have "package com.myfirm.program" on the first line.I compiled the application with:
javac -d . File1.java File2.java File3.java (etc...)
the compiler created the directory: /home/user/src/com/myfirm/program and put all of the .class files in there.So how do I get the program to run? if I run from /home/usr/src
java File1
I get: Exception in thread "main" java.lang.NoClassDefFoundError: File1 (wrong name: com/myfirm/program/Program)
View Replies
View Related
Apr 14, 2015
I create 2 files:
CircleCalculationMethod.javaMain.java
In Main.java, How can i call method in CircleCalculationMethod.java ?
Should I put everything in same folder ??Should i do something like "import CircleCalculationMethod.java"Should i do something like create a package ...
I use Eclipse software
View Replies
View Related
Sep 19, 2014
The title of Question might seem old and previously asked.But I have a Question that what is difference between javaSE and Java EE.Although I knew what comes under JavaSE and What is under JavaEE.But My question is that.
What happens when we add PATH in our Environment Variable How does Eclipse or Other IDE use it?
Second Question is.
For Java SE we declare a Path Variable but for Java EE we do not add any library?(I know we add some jar file like for Servlet(Servlet-api.jar) and for EJB(Ejb.jar),But What is actaul difference?
View Replies
View Related
Oct 23, 2014
creating a program that will output something like this:
Enter an Integer: 1405302(user inputted)
Your integer contains 2 even digit(s), 3 odd digit(s), and 2 zero(s).
View Replies
View Related