I've defined a arrayList as following
List<List<RiskyPersons>> dataArray = new ArrayList<>();
Here is RiskyPersons Class
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
Then I've successfully added data and saved in dataArray ArrayList.
Following output is showing the saved ArrayList using SOP(dataArray);
[[RiskyPersons{sa3tenant=Homeless.SA3Tenant#3a7cc6b0, NumberofPersonInCategory=99}]]
I want to read this dataArray ArrayList and display values separately. How do I access "NumberofPersonInCategory" value?
From Java-8 and above one can use stream:
dataArray.stream()
.flatMap(List::stream)
.map(RiskyPersons::NumberofPersonInCategory)
.forEach(System.out::println)
I hope this will help you !
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public int getNumberofPersonInCategory() {
return NumberofPersonInCategory;
}
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
List<Integer> values = dataArray.parallelStream().flatMap(Collection::stream).map(RiskyPersons::getNumberofPersonInCategory)
.collect(Collectors.toCollection(ArrayList::new));
You'll need to iterate it twice as
for (List<RiskyPersons> rp : dataArray) {
for (RiskyPersons o : rp) {
System.out.println(o.NumberofPersonInCategory); // unrelated : but its bad naming convention
}
}
Related
class Item {
int id;
List<PriceDetails> priceDetails;
String itemName;
}
class PriceDetails {
int price;
}
I am getting multiple items in a JSON file. I am trying to filter priceDetails with empty price (not the items, just removing all the priceDetails in the list with empty price)
I am able to write Java code and its working as expected, but I don't know how to write using Java Streams. Can someone help me?
Thanks in advance.
Java Code :
public static List<Item> filterByEmptyPrice(List<Item> items) {
List<Item> result= new ArrayList<>();
for(int i=0;i<items.size();i++) {
List<PriceDetails> temp= new ArrayList<>();
for(int j=0;j<items.get(i).PriceDetails.size();j++) {
if(nonNull(items.get(i).PriceDetails) && nonNull(items.get(i).priceDetails.get(j).priceDetails.price)) {
temp.add(items.get(i).priceDetails.get(j));
}
}
items.get(i).priceDetails= temp;
result.add(items.get(i));
}
return result;
}
Your filterByEmptyTicketPrice() method doesn't compile with the Item and PriceDetails model you gave.
The correct loop based implementation would be:
public static List<Item> filterByEmptyTicketPrice(List<Item> items) {
List<Item> result = new ArrayList<>();
for (Item item : items) {
List<PriceDetails> temp = new ArrayList<>();
for (PriceDetails priceDetails : item.priceDetails) {
if (nonNull(priceDetails.price)) {
temp.add(priceDetails);
}
}
// bug: you mutate your method input here
item.priceDetails = temp;
result.add(item);
}
return result;
}
Also, as noted above, you're mutating the input items. The correct way to do this with streams and without mutating the input would be:
public static List<Item> filterByEmptyTicketPrice(List<Item> items) {
return items.stream()
.map(item -> new Item(filterPrices(item.priceDetails)))
.collect(Collectors.toList());
}
static List<PriceDetails> filterPrices(List<PriceDetails> priceDetailsList) {
return priceDetailsList
.stream()
.filter(priceDetails -> priceDetails.price != null)
.collect(Collectors.toList());
}
This example assumes you've added a new Item constructor such as:
public Item(List<PriceDetails> priceDetails) {
this.priceDetails = priceDetails;
}
As others mentioned, you should update the model to use getters to access priceDetails and price making them private in your Item and PriceDetails classes.
I want to add the name of array in the class to jList as below.
How can it be?
this is the method in display class
public void dataToLocal(List<XDataObject> data, XServiceType xst, XServiceOperation operation) {
if(operation.getName().equals(SNOWTAMSubscriberServiceInterface.OP_PUBLISSNOWTAM)) {
SNOWTAMPublication snowtamPublication =
(SNOWTAMPublication)data.get(0).getValue(); //This read an array with 5 values.
SNOWTAM snowtam = snowtamPublication.getSNOWTAM()[0]; //This read read the array and its contents.
jList1.add((Component) Arrays.asList((snowtamPublication.getSNOWTAM()[0]).toString())); //Here I want to add the name of Array to be as below
}
}
This is SNOWTAMPublication which is only get and set methods for array.
protected SNOWTAM[] snowtam;
public SNOWTAM[] getSNOWTAM() {
if(snowtam == null)
{
snowtam = new SNOWTAM[0];
}
return snowtam;
}
public void setSNOWTAM(SNOWTAM[] _value) {
this.snowtam = _value;
}
The picture
You could try:
<instance>.getClass().getSimpleName()
Below is the response i am getting from the server,
{
"section_id": "[24,1,5,2]"
}
and I am using GSON library
public class SectionModel {
#SerializedName("section_id")
private String mSectionId;
public String getmSectionId() {
return mSectionId;
}
public void setmProgramName(String mSectionId) {
this.mSectionId = mSectionId;
}
}
I am able to get the value "[2,18,25,26]" and store it in a String.
Now how am I supposed to get those values from String and store in an Integer arraylist.
Try this method in your code:
public ArrayList<Integer> returnArrayList(String parsetest){
ArrayList<Integer> integerArrayList= new ArrayList<>();
parsetest=parsetest.replace("[", "");
parsetest=parsetest.replace("]", "");
String[] list = parsetest.split(",");
for (String item : list) {
integerArrayList.add(Integer.valueOf(item));
}
return integerArrayList;
}
Feel free to ask any doubt in the method.
I have two classes. One that has the array (ArrayStorage) and the other (ArrayConsumer) has just a variable that will act as a simple reference to an array.
I add a new element to the array using $my_array. Then I check to see if the new element is visible in the $obtained_array. But the test fails because it cannot find the new element. They act like they were different arrays. Shouldn't they point to the same array?
public function testArrayMadness() {
$arrayStorage = new ArrayStorage();
$my_array = $arrayStorage->getArray();
$arrayConsumer = new ArrayConsumer($my_array);
$obtained_array = $arrayConsumer->getArray();
$my_array[3]='c';
$this->assertContains('c', $obtained_array);
}
}
class ArrayStorage {
private $my_array=[1=>'a',2=>'b'];
function getArray() { return $this->my_array; }
}
class ArrayConsumer {
private $obtained_array;
function __construct($array) { $this->obtained_array=$array; }
function getArray() { return $this->obtained_array; }
}
Update:
I did the same on test in Java, it gives me an indexOutOfBoundsException. Does that mean both php and java works the same way in this aspect or is there something wrong with my code?
#Test
public void testArrayMadness() {
ArrayStorage arrayStorage = new ArrayStorage();
List<String> my_list = arrayStorage.getList();
ArrayConsumer arrayConsumer = new ArrayConsumer(my_list);
List<String> obtained_array = arrayConsumer.getList();
my_list.add("c");
assertEquals("c", obtained_array.get(3));
}
}
class ArrayStorage {
private List<String> my_list;
public ArrayStorage() {
my_list = new ArrayList<>();
my_list.add("a");
my_list.add("b");
}
public List<String> getList() { return my_list; }
}
class ArrayConsumer {
private List<String> obtained_list;
public ArrayConsumer(List<String> list) {
this.obtained_list = list;
}
public List<String> getList() { return this.obtained_list; }
}
PHP arrays are not objects, they are assigned by value:
$a = [1,2,3];
$b = $a;
$b[2] = 99;
print_r($b); // 1,2,99
print_r($a); // 1,2,3
A workaround is to use reference signs & (a bad idea generally) or ArrayObjects:
$a = new ArrayObject([1,2,3]);
$b = $a;
$b[2] = 99;
print_r($b); // 1,2,99
print_r($a); // 1,2,99
return reference array using & operator
something like return &$this->my_array;
I've got a method called removeSup which is supposed to remove an object Supplement from a list of supplements.
this is the code for the method:
private static void removeSup(Supplement supToRemove, List<Supplement> listToRemoveFrom) {
Iterator<Supplement> iterator = listToRemoveFrom.iterator();
while(iterator.hasNext()){
if(iterator.next().equals(supToRemove)){
iterator.remove();
}
}
}
there is a class called magazine which defines the list of supplements.
public class Magazine {
private List<Supplement> supList;
public List<Supplement> getSupList() {
return this.supList;
}
public void setSupList(List<Supplement> supList) {
this.supList = supList;
}
public Magazine(Double cost, String _name){
this.supList = new ArrayList<>();
this.weekCost = cost;
this.name = _name;
}
}
the class supplement has the following constructor
public Supplement(String _name, Double _price, String _magName ){
this.name=_name;
this.price=_price;
this.magName = _magName;
}
in the main class client there is a search that the user can do to remove a certain Supplement
private static void searchSup(){
System.out.println("Search for Supplement");
String search = scanner.nextLine();
for (Supplement sup : magazine.getSupList()) {
if (!sup.getSupName().equalsIgnoreCase(search)) {
//do something
}
else{
removeSup(sup,magazine.getSupList());
}
}
}
the main method in the client class is as follows:
private Magazine magazine;
public static void main(String[] args) {
magazine = new Magazine(3.0, "pop");
List<Supplement> startList = new ArrayList<>();
startList.add(new Supplement("Nat Geo", 3.0,"pop"));
startList.add(new Supplement("Discovery", 5.0,"pop"));
startList.add(new Supplement("Health", 6.3,"pop"));
startList.add(new Supplement("IT", 8.3,"pop"));
magazine.setSupList(startList);
searchSup();
}
When I run this program and type any of the added supplements, i get an error
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Client.searchSup(Client.java:131)
at Client.searchSup(Client.java:140)
at Client.main(Client.java:588)
is it the for loop i am using to search giving me an error? if so how would i go about fixing this?
You generally shouldn't modify a Collection while iterating over it. It's fine to modify elements, but you really shouldn't remove something from a Collection while iterating. See here: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html. Also, the Javadoc for ConcurrentModificationException may be helpful.
You might try returning a new list with the Supplement removed:
private static List<Supplement> removeSup(Supplement supToRemove, List<Supplement> listToRemoveFrom) {
List<Supplement> filteredSupplements = new ArrayList<Supplement>();
for(Supplement supplement : listToRemoveFrom) {
if(!suppplement.equals(supToRemove)){
filteredSupplements.add(supplement);
}
}
return filteredSupplements;
}
It seams that the "magazine" is local var in the method of main, not accessible to searchSup.Fix it like
private void searchSup(Magazine magazine)
{
//...
}
and more details if you can provide, the codes in Line 131 and 140 will be helpful.
I figured out that the search i was doing was not working with what i wanted to do so i created a method which returns an integer of the Supplement in the list.
private static int indexOfSup(List<Supplement> supSearchList, String nameOfSup) {
for (Supplement sup : supSearchList) {
if (sup.getSupName().equalsIgnoreCase(nameOfSup)) {
return supSearchList.indexOf(sup);
}
}
return -1;
}
i then use this integer to remove from the list.
a simple List.Remove(index) worked fine
Thanks for all the replies.