How to remove comma from HashSet String java - java

I have a HashSet String ['a','b','c']. How can I print the String abc?
My code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
HashSet<Character>h=new HashSet<>();
h.add('a');
h.add('b');
h.add('c');
// if here i am print HashSet element then print
System.out.println(h); //[a,b,c]
// now i HashSet convert in String
String res=h.toString();
// when i try to print String then print [a,b,c]
System.out.println(res); // [a,b,c]
//but i am not interest in this result becuase i wnat to print only abc remove all brackets [] ,and , commas
}

You just have to use String.join() as followed
System.out.println(String.join("",h));

If you are using Java 8 or later then you can use Java Stream API, or Iterable.forEach():
public class HashSetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c", "d", "e"));
System.out.println("System.out.println(set): " + set);
System.out.print("Using .forEach() method: ");
set.forEach(System.out::print);
System.out.println();
System.out.print("Using Stream API: ");
set.stream().forEach(System.out::print);
System.out.println();
}
}
The output will be:

Related

Java Collections-the number of words without repetition

I wan to create a method for which we give text(String) as an input argument.
The method will return the number of words without repetition.
For example: "cat, dog, Cat, Bird, monkey"
return value:4
How can I compare each Collections item with each other?
What I already have:
public class WordsCounter {
public static void main(String[] args) {
uniqueWordsCounter("cat, dog, Cat, Bird, monkey");
}
public static void uniqueWordsCounter(String text) {
String processedText = text.toLowerCase().replaceAll(",", "");
String[] words = processedText.split("\\s");
List<String> wordsList = Arrays.asList(words);
}
}
One way is to use the distinct() operation from the stream API:
import java.util.*;
public class WordsCounter {
public static void main(String[] args) {
uniqueWordsCounter("cat, dog, Cat, Bird, monkey");
}
public static void uniqueWordsCounter(String text) {
String[] words = text.toLowerCase().split(",\\s*");
List<String> wordsList = Arrays.asList(words);
System.out.println(wordsList);
System.out.println("Count of distinct elements: "
+ wordsList.stream().distinct().count());
}
}
Example run:
$ java Demo.java
[cat, dog, cat, bird, monkey]
Count of distinct elements: 4
Note splitting on comma followed by optional whitespace instead of your replacing commas and then splitting, to help simplify things.
You can use a set to keep track of all the unique elements present in your string after you separate it using the delimiter ","
In your example, you are keeping cat and Cat as same ( ignoring case ) . Thus, you can use this logic.
public class WordsCounter {
public static void main(String[] args) {
int count = uniqueWordsCounter("cat,dog,Cat,Bird,monkey");
System.out.println(count);
}
public static int uniqueWordsCounter(String text) {
String str[] = text.split(",");
Set<String> set = new HashSet<>() ;
for( String temp : str)
{
if ( !set.contains(temp.toLowerCase()))
{
set.add(temp);
}
}
return set.size();
}
}
and the output is
4

Reverse a list using ListIterator and skip certain position of character (Java)

I have a task asking for me to print out the given list of strings, skipping every second string. Then, prints the list of strings in reverse order, skipping every second string. All output should be printed on the same line.
For example, if the list of strings is ["a", "b", "c", "d"], the output should be "acdb". If the list of strings is ["a", "b", "c"], the output should be "acca".
import java.util.List;
import java.util.ListIterator;
public class ListPrintStrings {
public static void printStrings(List<String> strings) {
// write your code here
ListIterator<String> stringWithIterator = strings.listIterator(strings.size());
while(stringWithIterator.nextIndex() == 1){
stringWithIterator.next();
stringWithIterator.remove();
}
for(String s: strings){
System.out.print(s);
}
}
}
I have no idea how to reverse the list with a ListIterator and how to return the string together
Failures (3):
=> org.junit.ComparisonFailure: The ArrayList had an odd number of elements. Check that your solution can handles an odd number of elements. expected:<a[ceeca]> but was:<a[bcde]>
=> org.junit.ComparisonFailure: expected:<a[cdb]> but was:<a[bcd]>
=> org.junit.ComparisonFailure: expected:<hello[learningisfunjavaworld]> but was:<hello[worldlearningjavaisfun]>
These are the error I have. Thank for any help/ hints.
Try this.
public static void printStrings(List<String> strings) {
ListIterator<String> i = strings.listIterator();
while (i.hasNext()) {
System.out.print(i.next());
if (i.hasNext())
i.next();
}
while (i.hasPrevious()) {
System.out.print(i.previous());
if (i.hasPrevious())
i.previous();
}
System.out.println();
}
public static void main(String[] args) {
printStrings(List.of("a", "b", "c", "d"));
printStrings(List.of("a", "b", "c"));
}
output:
acdb
acca

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.

Removing special characters from string

I want to parse this string into a list and return {1.193493, 54.6333, 2.093077, 31.6235, 6.175355, 21.6479}. How do I get rid of the square brackets???? I used a for loop and replace but it doesn't work.
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]"
String[] parsed = st.split(",");
for (String next : parsed) {
next.replace("//[", "").replace("//]", "");
}
replace() works with plain Strings, not regex. Therefore you can simply use:
next.replace("[", "").replace("]", "");
Also notice that you need to assign it to some string variable; assigning it to need won't work (won't modify elements in parsed array).
You should actually remove the braces first and split later, like this:
String[] parsed = st.replace("[", "").replace("]", "").split(",");
You can do it all at one time with this regex:
(?:\D*(\d*\.\d*))+
You can do this with one line:
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
Full code:
package com.stackoverflow;
import java.util.Arrays;
import java.util.List;
public class Demo
{
public static void main(String[] args)
{
String t = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
for(String s : list)
{
System.out.println(s);
}
}
}
Converts string to list of strings and prints it. If you need to convert strings to doubles, use Double.parseDouble(s) in loop.
You could achieve your goal in two steps.
1) Remove all special characters except comma (,)
2) Then split by comma (,)
public static void main(String[] args) {
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
String[] parsed = st.replaceAll("[^\\d.,]+", "").split(",");
}
Output:

Sorting a String using java collections

I am attaching following code and i want to sort this as
class sort{
public static void main(String args[])
{String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
List f=new ArrayList();
f.add(st);
Collections.sort(f);
System.out.println("after sortting "+f);
}
}
I want output as:
a
is
kiran
this
But i am getting an exception as:-
Exception in thread "main" java.lang.ClassCastException: java.util.StringTokenizer cannot be cast to java.lang.Comparableat java.util.Collections.sort(UnknownSource)atcom.sort.main(Sort.java:18)
Change your code. There are some mistakes you need to correct.
String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
List<String> f=new ArrayList<>(); // use String type list
while (st.hasMoreTokens()){ // add all tokens by iterating st
f.add(st.nextToken()); // add tokens to list
}
Collections.sort(f);
System.out.println("after sorting "+f);
Out put:
after sorting [a, is, kiran, this]
Now you are getting sorted list
The problem is here:
f.add(st);
You are adding StringTokenizer to the list, instead of adding the individual tokens. Changing the code to use generics would have helped: if you declare your List as List<String>, the code wouldn't compile, pointing you in the right direction:
List<String> f=new ArrayList<String>();
Add a while loop to collect tokens from st, and add them to f one by one.
P.S. Since this is almost certainly a learning exercise, I am not going to spoil the fun for you by completing your code.
You can also use hasMoreElements() and nextElement()
class sort{
public static void main(String args[]) {
String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
ArrayList<String> f=new ArrayList<String>(); // use String type list
while (st.hasMoreElements()){ // add all by iterating st
f.add((String) st.nextElement()); // add tokens to list
}
Collections.sort(f);
System.out.println("after sorting "+f);
}
}
Consider using String.split() to split your string.
Class names should be nouns,
method names should be verbs or verb phrases,
and you should use generics.
public static void main(String[] arguments)
{
String input = "this is hootberry sause";
String[] inputArray;
List<String> inputList = new ArrayList<String>();
inputArray = input.split(" ");
Collections.addAll(inputList, inputArray);
Collections.sort(inputList);
System.out.println("Before sort: " + input);
System.out.println("After sort: " + inputList);
}

Categories

Resources