I am a beginner in java. I want to read elements one by one in sublist.
public class ListFirst {
public static void main(String[] args) {
List<Integer>list1= Arrays.asList(10,20,30,40);
List<Integer>list2=Arrays.asList(100,200,300,400);
List<List<Integer>>bigList= new ArrayList<>();
// I want to access an element of bigList one by one. how to do that?
}
}
If there is no sublist I can print using for loop upto list.size() and list.get() to print but here element is list itself..so I dont know how to read. could you please help me with that.
I modified your code to achieve what you wanted to do:
public class ListFirst {
public static void main(String[] args) {
List<Integer>list1= Arrays.asList(10,20,30,40);
List<Integer>list2=Arrays.asList(100,200,300,400);
List<List<Integer>>bigList= new ArrayList<>();
bigList.add(list1);
bigList.add(list2);
for (List<Integer> list : bigList) {
for (Integer i : list) {
System.out.print(i.intValue() + " ");
}
}
}
}
An alternative would be to not use nested List for storing your Integers:
public static void main(String[] args) {
List<Integer>list1= Arrays.asList(10,20,30,40);
List<Integer>list2=Arrays.asList(100,200,300,400);
// bigList is a list of Integers not list of lists
List<Integer>bigList= new ArrayList<>();
bigList.addAll(list1); // add all elements from list1
bigList.addAll(list2); // add all elements from list2
for (Integer i : bigList) {
System.out.print(i.intValue() + " ");
}
}
Assuming that the lists have bee added to bigList, you can iterate it using the for-each loop as shown below:
bigList.add(list1);
bigList.add(list2);
for (List<Integer> list : bigList) {
System.out.println(list);
}
DEMO
Using the traditional loop, you can print bigList as shown below:
for (int i = 0; i < bigList.size(); i++) {
System.out.println(bigList.get(i));
}
You can do the following:
bigList.stream()
.flatMap(Collection::stream)
.forEach(x -> System.out.println(x));
Output:
10
20
30
40
100
200
300
400
Related
I am using a 2D LinkedHashSet for my program. I was wondering how I can iterate through the two dimensional HashSet and print its contents without doing this:
System.out.println(name of initialized HashSet)
Here is my code for initialization of the 2D LinkedHashSet:
LinkedHashSet<LinkedHashSet<String>> block = new LinkedHashSet<LinkedHashSet<String>>();
You can use 2 loops for this, similar to how you would for an array:
for (Set<String> innerSet : block) {
for (String string : innerSet) {
System.out.println(string);
}
}
You can also use streams to print each element:
block.stream()
.flatMap(Collection::stream)
.forEach(System.out::println);
If one wants to use a functional solution, one could use the following:
Ideone demo
import java.util.LinkedHashSet;
public class Streamify {
public static void main (final String... args) {
final LinkedHashSet<LinkedHashSet<String>> block = new LinkedHashSet<>();
final LinkedHashSet<String> lineOne = new LinkedHashSet<>();
lineOne.add("Hello");
lineOne.add("World");
block.add(lineOne);
final LinkedHashSet<String> lineTwo = new LinkedHashSet<>();
lineTwo.add("Hi");
lineTwo.add("Universe");
block.add(lineTwo);
block.forEach(line -> {
line.forEach(System.out::print);
System.out.println();
});
}
}
I'm trying to get highest price of a product. I'm able to store the prices in an object.
I want to know how to get the maximum value from that object. Below is my code!
public class amazon {
static WebDriver driver;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C://Selenium/chromedriver.exe");
driver = new ChromeDriver();
driver.get("xyzzz.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
amazon az = new amazon();
az.run();
}
public void run() throws Exception {
List<Object> obj = new ArrayList<Object>();
List<WebElement> tag = driver.findElements(By.xpath("//span[#class='a-price-whole']"));
int i;
for(i=0; i<tag.size(); i++) {
obj.add(tag.get(i).getText());
}
System.out.println(obj);
driver.close();
}
Output i have..
[64,900, 99,900, 1,23,900, 64,900, 64,900, 69,900, 64,900, 64,900, 1,23,900, 52,900]
You first need to convert the numbers to int, and than you can use Collections.max on the list
List<Integer> prices = new ArrayList<>();
List<WebElement> tags = driver.findElements(By.xpath("//span[#class='a-price-whole']"));
for (WebElement tag: tags) {
prices.add(Integer.parseInt(tag.getText().replace(",", "")));
}
System.out.print(Collections.max(prices)); // 123900
Map the strings to ints (or longs, or some type of currency), then you can get the max using a Comparator
int max = driver.findElements(By.xpath("//span[#class='a-price-whole']")).stream()
.map(WebElement::getText)
.map(s -> s.replace(",", ""))
.map(Integer::parseInt)
.max(Integer::compare)
.get();
create an int and call it max (=0), run on each element of the list using a loop (for loop recommended), on each element, check if its bigger than max, if yes, put the value in max,
here is a little code, in case the list is called "list", change it to whatever you want
int max=0;
for (int i : list){
if (i >max)
max=i;
}
System.out.println(max) //print the maximum value of the array
Hi I have an arraylist of arraylist in this format:
[[val1, val2],[val3,val4],[val1,val2],[val1,val5]]
and would like to get the unique set of arraylists:
[[val1, val2],[val3,val4],[val1,val5]]
I have tried the following:
Set<String> uniques = new HashSet<>();
for (ArrayList<String> sublist : mappedEntities) {
uniques.addAll(sublist);
}
but this merges all the values of the internal arraylist together
can use Java 8 Collection Stream Distinct,
return in Set datatype :
Set<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toSet());
if you want return in List :
List<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toList());
Why not simply put them in a Set like this?
Set<List<String>> uniques = new HashSet<>(mappedEntities);
Your mistake is that you are flattening the inner lists and putting their items in the set separately.
The issue here is that you need a Set of ArrayList Set<ArrayList<String>>, but you are using a Set of Strings Set<String> instead.
Given the list :
List<List<String>> mappedEntities = Arrays.asList(Arrays.asList("val1", "val2"),
Arrays.asList("val3", "val4"),
Arrays.asList("val1", "val2"),
Arrays.asList("val1", "val5"));
All you need to do is just declare the set and use the addAll().
Set<List<String>> mySet = new HashSet<>();
mySet.addAll(mappedEntities);
Since a set can hold only unique values, all duplicates will not be added to the set (No need to explicitly check this). You can now print it out :
mySet.forEach(System.out::println);
Or more simply, initialize the HashSet using the list mappedEntities :
Set<List<String>> mySet = new HashSet<>(mappedEntities);
I am beginner on STACKOVERFLOW but i to try solve your problem
I think you want like this..
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int n = 3;
// Here aList is an ArrayList of ArrayLists
ArrayList<ArrayList<String> > aList =
new ArrayList<ArrayList<String> >(n);
// Create n lists one by one and append to the
// master list (ArrayList of ArrayList)
ArrayList<String> a1 = new ArrayList<String>();
a1.add("1");
a1.add("2");
aList.add(a1);
ArrayList<String> a2 = new ArrayList<String>();
a2.add("11");
a2.add("22");
aList.add(a2);
ArrayList<String> a3 = new ArrayList<String>();
a3.add("1");
a3.add("2");
aList.add(a3);
Set<ArrayList<String>> uniques = new HashSet<ArrayList<String>>();
for (ArrayList<String> sublist : aList) {
uniques.add(sublist);
}
System.out.println("Your Answer");
for (ArrayList<String> x : uniques)
System.out.println(x);
}
}
try this code:
public class B {
public static void main(String[] args) throws Exception {
List<List<String>> list= Arrays.asList(
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c","d"));
Set<List<String>> uniques = new HashSet<>();
for (List<String> sublist : list) {
if(!uniques.contains(sublist))
uniques.add(sublist);
}
System.out.println(uniques);
}
}
output:
[[a, b, c], [a, b, c, d]]
How to check whether a specific String is present inside ArrayList<String[]>?
Whether I need to iterate each item and check for the string or any specific method for this purpose is present (like ArrayList.contains() )?
Tried ArrayList.contains() but not working in my case.
It is not an ArrayList <String> it is ArrayList<String[]> so this question is not a duplicate one and am asking this for a curiosity whether any special method is present or not
This is a example program to get what you asked for... hope it helps
public static void main(String[] args) {
ArrayList<String []> a = new ArrayList<>();
String b[] = {"not here","not here2"};
String c[] = {"not here3","i'm here"};
a.add(b);
a.add(c);
for (String[] array : a) {// This loop is used to iterate through the arraylist
for (String element : array) {//This loop is used to iterate through the array inside the arraylist
if(element.equalsIgnoreCase("i'm here")){
System.out.println("found");
return;
}
}
}
System.out.println("match not found");
}
You can do it easily with streams:
String contains;
List<String[]> strings;
boolean isPresent = strings.stream().flatMap(Arrays::stream).anyMatch(contains::equals);
Well, you need to traverse whole list and then traverse each array inside it to find the item.
String valToBeSearched="abc";
for(String [] arr: list)
{
for(String str: arr)
{
if(str.equals(valToBeSearched)){ // do your stuff}
}
}
Using Java 8 streams, you can do this:
public boolean containsString(List<String[]> list, String s) {
// Gives you a Stream<String[]>.
return list.stream()
// Maps each String[] to Stream<String> (giving you a
// Stream<Stream<String>>), and then flattens it to Stream<String>.
.flatMap(Arrays::stream)
// Checks if any element is equal to the input.
.anyMatch(Predicate.isEqual(s));
}
You could iterate over the ArrayList with two for-each loops:
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String[]> arrayList = new ArrayList<String[]>();
String[] fruit = {"Apple", "Banana"};
String[] pets = {"Cat", "Dog"};
arrayList.add(fruit);
arrayList.add(pets);
System.out.println(Arrays.deepToString(arrayList.toArray())); //[[Apple, Banana], [Cat, Dog]]
System.out.println(arrayListContains(arrayList, "Apple")); //true
System.out.println(arrayListContains(arrayList, "Orange")); //false
}
public static boolean arrayListContains(ArrayList<String[]> arrayList, String str) {
for (String[] array : arrayList) {
for (String s : array) {
if(str.equals(s)) {
return true;
}
}
}
return false;
}
}
Try it here!
Try to take a look at Guava Iterables.concat().
It can be used to flatten Iterable of Iterables, i'm not sure it will work on an Iterable of Array but it's just a little transformation...
If you can flatten your list, you could then use the "contains" method on the result.
Apologies for the newbie question, but what's the proper way to get a Set (say LinkedHashSet) in reverse order? For Collections there's Collections.reverse(Collection c), but how does one do it for a Set with ordered elements (like a LinkedHashSet)?
Sets are not ordered in general, so to preserve the sorting, after sorting the set as a list, you would need to use a known iteration order implementation of Set, such as LinkedHashSet
List list = new ArrayList(set);
Collections.sort(list, Collections.reverseOrder());
Set resultSet = new LinkedHashSet(list);
You could also use TreeSet with a comparator, but that is not as fast as the ArrayList method above.
public class LargestArray {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
Set<Integer> set = new TreeSet<>();
set.add(10);
set.add(20);
set.add(7);
set.add(4);
set.add(1);
set.add(2);
set.add(3);
set.add(4);
System.out.println("after Sorting");
for(int i : set) {
System.out.print(" " + i);
}
al.addAll(set);
set.clear();
Collections.reverse(al);
System.out.println();
System.out.println("After Reverse");
for (int i : al) {
System.out.print(" " + i);
}
}
}
output = after Sorting
1 2 3 4 7 10 20
After Reverse
20 10 7 4 3 2 1
Check this out
http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#descendingSet()
If you use a TreeSet you can get reverse order by calling descendingSet.
I will explain you with an example. Comments are added in mid of the code for better understanding.
public class ReverseLinkedHashSet {
public static void main(String[] args) {
// creating a LinkedHashSet object which is
// of type String or any. Will take a example of String.
HashSet<String> cars = new LinkedHashSet<String>();
// adding car elements to LinkedHashSet object as below
cars.add("Toyato");
cars.add("Hundai");
cars.add("Porshe");
cars.add("BMW");
// Iterating using enhanced for-loop to see the order.
System.out.println("Insertion Order: Iterating LinkedHashSet\n");
for(String car : cars) {
System.out.println(car);
// Output will be as below
//Toyato
//Hundai
//Porshe
//BMW
}
// Now convert to ArrayList to rearrange to reverse
// the linkedHashset
List<String> listOfCars = new ArrayList<String>(cars);
// to reverse LinkedHashSet contents
Collections.reverse(listOfCars);
// reverse order of LinkedHashSet contents
// can be done as below
System.out.println("\n\n\nReverse Order of LinkedHashSet\n");
for(String car : listOfCars) {
System.out.println(car);
// Output will be as below
//BMW
//Porshe
//Hundai
//Toyato
}
}
}
Also, I suggest not to use LinkedhashSet without a strong reason. For a complex application, it will reduce the performance. Use HashSet instead.
Java 8, I using solution below,
Set<String> setTest = new HashSet<>();
setTest.add("1");
setTest.add("2");
setTest.add("3");
List<String> list = new ArrayList<>(setTest);
list.sort(Collections.reverseOrder());
Set<String> result = new LinkedHashSet<>(list);
for (String item: result) {
System.out.println("---> " + item);
}
Result:
---> 3
---> 2
---> 1
Work for me.