I'm curious if there's a syntactic way to extend JSONArray such that I can then use it in a for(:) loop as I can a List.
So, instead of having to do:
for(int i = 0; i< myJsonArray.length(); i++){
myJsonArray.getString(i);
}
I would like to do
for(String s : myJsonArray);
I realize that I need to make sure that in the above example the object in the array is indeed a String, but given that JSONArrays can only handle a few types that shouldn't be problem.
With a slight adjustment to the desired syntax:
for(String s : iterable(myJsonArray))
Then write the iterable method something like so:
public static Iterable<String> iterable(final JSONArray array) {
return new Iterable<String> {
Iterator<String> iterator() {
return new Iterator<String> {
int i = 0;
boolean hasNext(){
return i < array.length();
}
String next(){
return array.getString(i++);
}
void remove(){
throw new RuntimeException(); //implement if you need it
}
}
}
};
}
I realize that I need to make sure that in the above example the object in the array is indeed a String
Well not really as if it isn't a String, it will be coerced to a String anyway.
This is known as the enhanced for loop. ref
I believe the collection needs to implement Iterable to get that functionality. (or you need an Iterable)
This is how you would do it, use enhanced for loop with your class.
JsonArray does not; so no you can't :-)
Direct is a class that contains 2 get methods and one of them is getName().
In the following code, I am using an array and it works correctly.
But if I want to store it in a LinkedList instead of an array, how do I iterate and reach the getName() method. I am able to iterate fine if is just a list of common primitives such as Strings but in this case where it is a list of class, I am confused on how to reach the getName() method. Thanks for helping.
private LinkedList<Direct> directList= new LinkedList();
private ListIterator<Direct> iterator = directList.listIterator();
private Direct[] direct = new Direct[100];
private int find(String name){
for (int x=0; x < direct.length; x++){
if (direct[x] != null)
if (direct[x].getName().equals(name)){
return x;
}
}
return -1;
}
Simply use directList.get(i). But you shouldn't use the index based get() method with LinkedList as it's very slow. Instead, you should use an iterator (or a for each loop, which is essentially the same):
int cnt = 0;
List<Direct> list = new LinkedList<>();
for (Direct d : list) {
if (name.equals(d.getName())) {
return cnt;
}
cnt++;
}
With an iterator:
for (Iterator<Direct> it = list.iterator(); it.hasNext();) {
Direct d = it.next();
if(name.equals(d.getName())){
System.out.println("matches");
}
}
In Java 8 you can also use the following solution (which will be slower, as it filters the entire list):
Direct d = list.stream().filter(direct -> direct.getName().equals(name)).findFirst();
There are (at least) two ways:
// generally easier to read if you don't need access to the iteration number.
for( Direct d : directList )
{
d.getName();
// ...
}
or use List#get(int) method (Although this is valid, since you are using a LinkedList this solution is O(n^2) instead of O(n) it shouldn't be used.)
for( int i = 0; i < directList.size(); ++i )
{
directList.get(i).getName();
}
Good day All,
Normally, I will print all the content in List by look the list.size() and assign it to an object and print the object value. The following is my example code:
List ccUserList = new ArrayList(); // Here I declare a List
Collection ccGroupCol = new ArrayList(); // Here I declare a collection
CCuserBO bo = null;
ccUserList = getSummaryList();
for(int i = 0, i < ccUserList.size() , i++){
bo = ( CCUserBO ) ccUserList.get(i);
System.out.println(bo.userName);
}
I would like to ask about the way to print content in Collection.
Since Collection no have .get() function.
The following in the code that I try in Collection:
CCuserBO newBo = null;
ccGroupCol = getSummaryList();
Iterator iterator = ccGroupCol.iterator();
while ( iterator.hasNext()){
newBo = iterator.next(); //error here, Type mismatch: cannot convert from Object to //Object[]
System.out.println("....");
}
If you simply want to print all elements of a Collection just sysout Collection directly it will provide you the following form in output: [element1, element2, ....] because toString() method is overrided and implemented to provide such output for all Collection classses.
By using Iterator you can get the element one by one:
Iterator iterator = ccGroupCol.iterator();
while ( iterator.hasNext()){
newBo = (**type cast here to particular newBo object type**)iterator.next();
System.out.println(newBo);//here whatever you implemented in toString() method
// in newBo type class(if you did so), you will get that type of output, if you do not override
//toString() to provide your implementation,you will get default implementation in
//which it will show <the object class>#<its hash code>
}
Note: the return type of iterator.next() is Object type, so you must type cast it to avoid incompatible type exception. Or use Generics.
I found the solution. Here is the example code:
CCGroupBO newBo;
for(int i = 0 ; i < ccGroupCol.size() ; i++){
newBo = ( CCGroupBO ) ccGroupCol.toArray()[i];
System.out.println(newBo.getGroupName());
}
Thanks for all your help.
You can use the for loop to iterate the collection.
Collection collection= new ArrayList();
for (Object obj : collection) {
//Here you can type cast the obj then you can print.
}
As statet in comment, a faster solution for your own answer:
Collection<CCGroupBO> ccGroupCol = new ArrayList<CCGroupBO>()
…
CCGroupBO[] boArray = ccGroupCol.toArray();
for(CCGroupBO newBo : boArray){
System.out.println(newBo.getGroupName());
}
or even more direct:
Collection<CCGroupBO> ccGroupCol = new ArrayList<CCGroupBO>()
…
for(CCGroupBO newBo : ccGroupCol){
System.out.println(newBo.getGroupName());
}
depending on other circumstances there is even a nicer method:
class CCGroupBO {
…
public String toString() {
return getGroupName();
}
}
…
Collection<CCGroupBO> ccGroupCol = new ArrayList<CCGroupBO>()
…
System.out.println(ccGroupCol);
I have an ArrayList that contains Address objects.
How do I print the values of this ArrayList, meaning I am printing out the contents of the Array, in this case numbers.
I can only get it to print out the actual memory address of the array with this code:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i));
}
list.toString() is good enough.
The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.
Add toString() method to your address class then do
System.out.println(Arrays.toString(houseAddress));
From what I understand you are trying to print an ArrayList of arrays and one way to display that would be
System.out.println(Arrays.deepToString(list.toArray()));
since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object
solution
in your Address class override the toString() method like this
public class Address {
int addressNo ;
....
....
...
protected String toString(){
return Integer.toString(addressNo);
}
now when you call
houseAddress.get(i) in the `System.out.print()` method like this
System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called
You can simply give it as:
System.out.println("Address:" +houseAddress);
Your output will look like [address1, address2, address3]
This is because the class ArrayList or its superclass would have a toString() function overridden.
Hope this helps.
assium that you have a numbers list like that
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
if you print the list
//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
System.out.print(number);
}
//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));
//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));
//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);
Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?
If you have an ArrayList of arrays (e.g.
int[] arr = {1, 2, 3};
houseAddress.add(arr);
Then to print the array values you need to call Arrays.deepToString:
for (int i = 0; i < houseAddress.size(); i++) {
System.out.println(Arrays.deepToString(houseAddress.get(i)));
}
public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+" ");
}
}
I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:
System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));
Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:
With annonymous class:
houseAddress.forEach(new Consumer<String>() {
#Override
public void accept(String s) {
System.out.println(s);
}
});
lambda expression:
houseAddress.forEach(s -> System.out.println(s));
or by using method reference:
houseAddress.forEach(System.out::print);
This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.
Simplest way to print an ArrayList is by using toString
List<String> a=new ArrayList<>();
a.add("111");
a.add("112");
a.add("113");
System.out.println(a.toString());
Output
[111, 112, 113]
Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print((houseAddress.get(i)).toString());
}
This helped to me:
System.out.println(Arrays.toString(codeLangArray.toArray()));
public static void main(String[] args) {
List<Moyen> list = new ArrayList<Moyen>();
Moyen m1 = new Moyen();
m1.setCodification("c1");
m1.setCapacityManager("Avinash");
Moyen m2 = new Moyen();
m2.setCodification("c1");
m2.setCapacityManager("Avinash");
Moyen m3 = new Moyen();
m3.setCodification("c1");
m3.setCapacityManager("Avinash");
list.add(m1);
list.add(m2);
list.add(m3);
System.out.println(Arrays.toString(list.toArray()));
}
You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String
Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Note : You can even use an enhanced for loop for this as mentioned by me in another answer
if you make the #Override public String toString() as comments,
you will have the same results as you did.
But if you implement your toString() method, it will work.
public class PrintingComplexArrayList {
public static void main(String[] args) {
List houseAddress = new ArrayList();
insertAddress(houseAddress);
printMe1(houseAddress);
printMe2(houseAddress);
}
private static void insertAddress(List address)
{
address.add(new Address(1));
address.add(new Address(2));
address.add(new Address(3));
address.add(new Address(4));
}
private static void printMe1(List address)
{
for (int i=0; i<address.size(); i++)
System.out.println(address.get(i));
}
private static void printMe2(List address)
{
System.out.println(address);
}
}
class Address{
private int addr;
public Address(int i)
{
addr = i;
}
#Override public String toString()
{
Integer iAddr = new Integer (addr);
return iAddr.toString();
}
}
You can even use an enhanced for loop or an iterator like:
for (String name : houseAddress) {
System.out.println(name);
}
You can change it to whatever data type houseAddress is and it avoids unnecessary conversions
Make sure you have a getter in House address class and then use:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i)**.getAddress()**);
}
you can use print format if you just want to print the element on the console.
for(int i = 0; i < houseAddress.size(); i++) {
System.out.printf("%s", houseAddress.get(i));
}
Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i).toString());
}
A general example:
ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]
This is a simple code of add the value in ArrayList and print the ArrayList Value
public class Samim {
public static void main(String args[]) {
// Declare list
List<String> list = new ArrayList<>();
// Add value in list
list.add("First Value ArrayPosition=0");
list.add("Second Value ArrayPosition=1");
list.add("Third Value ArrayPosition=2");
list.add("Fourth Value ArrayPosition=3");
list.add("Fifth Value ArrayPosition=4");
list.add("Sixth Value ArrayPosition=5");
list.add("Seventh Value ArrayPosition=6");
String[] objects1 = list.toArray(new String[0]);
// Print Position Value
System.err.println(objects1[2]);
// Print All Value
for (String val : objects1) {
System.out.println(val);
}
}
}
JSON
An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.
Example using Google's Gson:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
...
public static void printJsonString(Object o) {
GsonBuilder gsonBuilder = new GsonBuilder();
/*
* Some options for GsonBuilder like setting dateformat or pretty printing
*/
Gson gson = gsonBuilder.create();
String json= gson.toJson(o);
System.out.println(json);
}
Add toString() method to your class
houseAddress.forEach(System.out::println);
Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object
changing the String datatype to the appropriate datatype or class object as desired.
ArrayList<String> teamRoster = new ArrayList<String>();
// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");
System.out.println("Current roster: ");
for (String playerName : teamRoster) {
System.out.println(playerName);
// if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}
I have a List containing HashMaps. Each HashMap in the list might have multiple key/value pairs. I want to indexOf on the list to find out the index of the element where the passed in HashMap is. However, the problem is that equals method of HashMap looks at all the entire entrySet while comparing. Which is not what I want.
Example:
List<HashMap> benefit = new ArrayList<HashMap>();
HashMap map1 = new HashMap();
map1.put("number", "1");
benefit.add(map1);
HashMap map2 = new HashMap();
map2.put("number", "2");
map2.put("somethingelse", "blahblah"); //1
benefit.add(map2);
HashMap find = new HashMap();
find.put("number", "2");
int index = benefit.indexOf(find);
if (index >= 0)
System.out.println(benefit.get(index).get("number"));
The above code does not print anything because of line with //1.
What do I have to do so that the above code actually prints 2?
Is there a way to implement comparable on the list so that I can define
my own?
I think you're looking for retainAll(), so you can compare only the elements you're interested in:
int index = myIndexOf(benefit, find);
...
static int myIndexOf(List<HashMap> benefit, Map find) {
int i = 0;
for (Map map : benefit) {
Map tmp = new HashMap(map);
tmp.keySet().retainAll(find.keySet());
if (tmp.equals(find)) {
return i;
}
i++;
}
return -1;
}
It's possible, of course, to declare your own subclass of List that overrides the indexOf method with this behaviour. However, I don't think that's a good idea. It would violate the contract of the indexOf method:
returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i)))
This would be confusing to someone else maintaining the code. You might then think that you could subclass HashMap to redefine equals, but that would violate the symmetry property of Object.equals().
The way you are trying to achieve your goal is wrong. The indexOf method works exactly as it should in this case. It is trying to find an exact match, not a partial one.
What you are trying to do, if I get it correctly, is to find a map in your list of maps that contains a specific entry. In this case, you should manually perform this search, by going through all the maps, calling containsKey (), and then comparing the value you are expecting to find with the value associated with the key.
The other way would be to create a proxy class around your List, and add a new method findMapWithEntry (String key, String value), which would perform this seach for you (the same search I described above).
Why not change the way you search?
List<Map> matchingBenefits = new ArrayList<Map>();
for (Map m : benefit) {
if (m.containsKey("number") && m.get("number").equals("2"))
matchingBenefits.add(m);
}
for (Map m : matchingBenefits) {
System.out.println(m.get("number"));
}
You can always override the indexOf method. Looking at the source for ArrayList:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
So it's not a very complex search algorithm at all. You may look at something like:
List benefit = new ArrayList(){
public int indexOf(Object o){
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
else {
for (int i = 0; i < size; i++) //traverse the hashmaps
Object key = ((HashMap)o).keySet().get(0); //assuming one pair
Object val = ((HashMap)o).valueSet().get(0);
if (
((HashMap)elementData[i]).containsKey(key) &&
((HashMap)elementData[i]).get(key).equals(val))
return i;
}
return -1;
};
My advice would be to consider a different data structure, perhaps writing your own one for it.
Given that you cannot change the design, would writing your own find method help?
The code below should work if I understood what you're trying to do and it runs in O(n)
public static String find(List<HashMap<String,String>> listMap, String key, String value) {
for(int i = 0; i < listMap.size(); i++)
if(listMap.get(i).get(key).equals(value))
return value;
return null;
}