How to iterate through a 2D LinkedHashSet and print its contents? - java

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();
});
}
}

Related

Not able to access individual element from sublist

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

How to get an String and the ArrayList stored in a Arraylist of objects of a class using Java stream

I have modified the code and trying to get an ArrayList and the String stored in an Arraylist of Objects on a specific condition(say 'str' string equal to 2). I'm not able to convert the Stream to ArrayList. Please help me understand what needs to be done to get the ArrayList from this stream.
I have a class 'SampleClass' like below:
import java.util.ArrayList;
public class SampleClass {
String str;
ArrayList<String> al;
String check;
public SampleClass(String str, ArrayList<String> al, String check) {
super();
this.str = str;
this.al = al;
this.check = check;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public ArrayList<String> getAl() {
return al;
}
public void setAl(ArrayList<String> al) {
this.al = al;
}
public String getCheck() {
return check;
}
public void setCheck(String check) {
this.check = check;
}
}
I have another class 'GetTheArrayListStoredInAnotherArrayList' like below where I'm trying to get the ArrayList stored inside the ArrayList of objects. Please correct me where I'm wrong.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public class GetTheArrayListStoredInAnotherArrayList{
public static void main(String[] args) {
String test = "qw,rer,try,try,erh5,wertgw45t,45";
ArrayList<String> al = new ArrayList<String>();
al.addAll(new ArrayList<String>(Arrays.asList(test.split(","))));
System.out.println(al);
ArrayList<SampleClass> sca = new ArrayList<SampleClass>();
SampleClass sc1 = new SampleClass("1", al,"ch1");
SampleClass sc2 = new SampleClass("2", al,"cc2");
SampleClass sc3 = new SampleClass("3", al,"fr3");
SampleClass sc4 = new SampleClass("4", al,"fg4");
sca.add(sc1);
sca.add(sc2);
sca.add(sc3);
sca.add(sc4);
ArrayList<String> als1 = null;
ArrayList<String> als = sca.stream().filter( s -> s.getStr().equals("2")).flatMap(sc -> sc.getAl().stream()).collect(Collectors.toCollection(ArrayList::new));
System.out.println(als);
String ch = (String) sca.stream().filter(s -> s.getStr().equals("1")).map(ac -> ac.getCheck());
System.out.println(ch);
}
}
I got the below error when I executed the code :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot cast from Stream<String> to String
at GetTheArrayListStoredInAnotherArrayList.main(GetTheArrayListStoredInAnotherArrayList.java:24)
Not entirely sure what you are trying to do, but you need to change your code a bit:
List<String> als = sca.stream()
.filter(s -> s.getStr().equals("2"))
.flatMap(sc -> sc.getAl().stream())
.collect(Collectors.toList());
A few things :
flatMap must return a Stream (in your case you are returning a List)
Collectors.toList makes no guarantee of the List in returns, so the assignment is to a List, not an ArrayList.
EDIT
This:
Stream<String> stream = sca.stream().filter(s -> s.getStr().equals("1"))
.map(ac -> ac.getCheck());
Will produce a Stream<String>. You can't simply cast that to a String, you have to collect/reduce that to whatever you want. Like let's say a List:
List<String> list = sca.stream()
.filter(s -> s.getStr().equals("1"))
.map(ac -> ac.getCheck())
.collect(Collectors.toList());
Or a single String for example:
String r = sca.stream()
.filter(s -> s.getStr().equals("1"))
.map(ac -> ac.getCheck())
.collect(Collectors.joining(","));
This is actually basic stuff... you should really study some samples and the documentation.
Change
ArrayList<String> als = sca.stream().filter( s -> s.getStr().equals("2")).flatMap( sc -> sc.getAl());
To
ArrayList<String> als = sca.get(0).getAl();
First you have to use List instead of ArrayList. So with List you code will looks like
List<String> als1 = null;
List<String> als = sca.stream().
filter(s -> s.getStr().equals("2")). //Comparing
map(s -> s.getAl()) // Converting List<SampleClass> to list of all al list inside all SampleClass in format List<List<Straing>>
.flatMap(ArrayList::stream) //Creating a flat list from list of list of List :: List<List<Straing>> --To--> List<String>
.collect(Collectors.toList()); // Collecting as list
I have commented this code with details. But here if there are two SampleCalss objects in the list with str=2 then it will merge the al list of both objects. hope it will help you .
I'm trying to get the ArrayList stored inside the ArrayList of objects.
Well, the basic algorithm is as follows: Filter sca so it only leaves elements where str is "2" -> Get a single element from all the left over elements -> Get the al stored inside of that element.
You have done the first part correctly:
sca.stream().filter( s -> s.getStr().equals("2"))
But now you need to get a single element from the filtered result (filter can result in multiple elements being left over), so you call findFirst:
.findFirst().get()
This get call will throw an exception if there is no element left after the filter. If you don't want it to throw an exception, you can replace it with an orElse call:
.findFirst.orElse(new SampleClass("", null))
If you use orElse, the method chain will evaluate to null if no element with str being "2".
Now you just need to get the array list by calling getAl():
.getAl();
Now we combine all this together:
ArrayList<String> als = sca.stream()
.filter( s -> s.getStr().equals("2"))
.findFirst().orElse(new SampleClass("", null)).getAl();

String inside ArrayList<String[]>

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.

Iterating through sets

I am writing a program that will receive a list of words. After that, it will store the repeated words and the non repeated into two different lists. My code is the following:
public class Runner
{
public static void run (Set<String> words)
{
Set<String> uniques= new HashSet<String>();
Set<String> dupes= new HashSet<String>();
Iterator<String> w = words.iterator();
while (w.hasNext())
{
if (!(uniques.add(w.next())))
{
dupes.add(w.next());
}
else
{
uniques.add(w.next());
}
}
System.out.println ("Uniques: "+ uniques);
System.out.println ("Dupes: "+ dupes);
}
}
However, the output for the following:
right, left, up, left, down
is:
Uniques: [left, right, up, down]
Dupes: []
and my desired would be:
Uniques: [right, left, up, down]
Dupes: [ left ]
I want to achieve this using sets. I know it would be way easier to just an ArrayList but I am trying to understand sets.
The reason for your problem is that the argument words is a Set<String>. A set by definition will not contain duplicates. The argument words should be a List<String>. The code also makes the mistake of calling w.next() twice. A call to the next() will cause the iterator to advance.
public static void run(List<String> words) {
Set<String> uniques= new HashSet<String>();
Set<String> dupes= new HashSet<String>();
Iterator<String> w = words.iterator();
while(w.hasNext()) {
String word = w.next();
if(!uniques.add(word)) {
dupes.add(word);
}
}
}
You are doing uniques.add(w.next()) twice. Why?
Also, don't keep calling w.next() - this makes the iteration happen. Call it once and keep a local reference.
Use:
String next = w.next();
if(uniques.contains(next)) {
// it's a dupe
} else {
// it's not a dupe
}

Sort a Set in reverse order

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.

Categories

Resources