Maximum distance between two different element in an array

I have a problem where I need to find the maximum distance between two different elements in an array.

For example: given an array 4,6,2,2,6,6,4 , the method should return 5 as the max distance.

I am able to solve the problem using two for loops but it is not an optimized solution. Am trying to optimize it by doing it in a single for loop.

here is my current solution:

int [] A = {4,6,2,2,6,6,4};
int N = A.length;
int result = 0;

for (int i = 0; i < N; i++){
    for (int j = i; j < N; j++) {
        if(A[i] != A[j]){
            result = Math.max(result, j - i);
        }
    }
}

// tried below code but it is not efficient
//      for (int i = 0; i < N; i++){
//          
//          if(A[N-1] != A[i]){
//              result = Math.max(result, N-1-i);
//          }
//      }

System.out.println(result);

How to make this better in terms of time complexity?

Solution:

Simple (not nested) loop is enough, but two cases should be taken into
account: either the best result is

  4,6,2,2,6,6,4
    ^         ^ - moving first

or

  4,6,2,2,6,6,4
  ^         ^   - moving last

for instance: [4, 2, 4, 4, 4] moving first brings the answer, when in case of [4, 4, 4, 2, 4] moving last should be used.

  int first = 0;
  int last = A.length - 1;

  // 1st case: moving "first"
  while (first < last) {
    if (A[first] == A[last])
      first++;
    else
      break;
  }

  int diff1 = last - first;

  first = 0;
  last = A.length - 1;

  // 2nd case: moving "last"
  while (first < last) {
    if (A[first] == A[last])
      last--;
    else
      break;
  }

  int diff2 = last - first;

  // result is the max between two cases
  int result = diff1 > diff2
    ? diff1
    : diff2;

So we have O(N) time complexity.

Edit: Let’s proof that at least one of the indexes is either 0 or length - 1. Let’s do it by contradiction. Suppose we have a solution like

  a, b, c, .... d, e, f, g
        ^ ..... ^  <- solution indexes (no borders)

Items to the left of c must be d, otherwise we can take a or b indexes and have an improved solution. Items to right of d must be c or we can once again push last index to the right and have a better solution. So we have

  d, d, c .... d, c, c, c
        ^ .... ^  <- solution indexes 

Now, since d <> c (c..d is a solution) we can improve the solution into

  d, d, c .... d, c, c, c
        ^ .... ^           <- solution indexes 
  ^       ....          ^  <- better solution

We have a contradiction (the supposed solution is not one – we have a better choice) and that’s why at least one index must be 0 or length - 1.

Now we have 2 scenarions to test:

  a, b, ..... y, z
     ^  ......   ^ <- moving first
  ^  ......   ^    <- moving last

We can combine both conditions into if and have just one loop:

  int result = 0;

  for (int i = 0; i < A.length; ++i)
    if (A[i] != A[A.length - 1] || A[0] != A[A.length - 1 - i]) {
      result = A.length - i - 1;

      break;
    }

Is it good idea to control program flow based on message from Exception?

For example I have a TCP server:

ServerSocket serverSocket = new ServerSocket(12345)
boolean doAccept = true;
while (doAccept) {
    try {
        serverSocket.accept();
    } catch (SocketException e) {
        if (serverSocket.isClosed()) {
            LOGGER.info("Server stopped.", e);
            doAccept = false;
        } else if (e.getMessage().equals("Too many open files")) {
            LOGGER.warn("Unable to accept. Will retry in 5 seconds.", e);
            Thread.sleep(5_000);
        } else {
            LOGGER.error("Socket error.", e);
            doAccept = false;
        }
    } catch (IOException e) {
        LOGGER.error("I/O error.", e);
        doAccept = false;
    }
}

If ServerSocket::accept throws a SocketException: Too many open files, I would like only to log the exception but keep running my TCP server thread and retry accept after a few sec sleep. But in any other cases server thread must be done.

Can I use here safely the message from exception and make sure exception message is always same on every implementation? Or exists any better way to detect that?

SOLUTION

Thank you guys for great answers. Only SocketException and not any subclasses can be catched in my example. Neither ServerSocket nor SocketException have any getStatusCode() method. So I choosed the following simplified solution for my example finally:

ServerSocket serverSocket = new ServerSocket(12345)
boolean doAccept = true;
while (doAccept) {
    try {
        serverSocket.accept();
    } catch (SocketException e) {
        if (serverSocket.isClosed()) {
            LOGGER.info("Server stopped.", e);
            doAccept = false;
        } else {
            LOGGER.warn("Unable to accept. Will retry in 5 seconds.",                 LOGGER.error("Socket error.", e);
            Thread.sleep(5_000);
        }
    } catch (IOException e) {
        LOGGER.error("I/O error.", e);
        doAccept = false;
    }
}

Solution:

No, this is definitely an anti pattern. Exception messages should be seen as human readable information, and nothing else. They are not meant to be programmatically evaluated. Period. ( and yes, there are systems that actually do programmatically look into messages – but that is more of a “meta” analysis, looking for “patterns”, not doing hard “string equals” checking )

Thing is: these exceptions aren’t under your control. Meaning: you won’t notice when their implementation changes. It is not very likely, but still possible that the exact content/layout of these messages changes at some point in the future. And then your whole code falls apart.

In other words: if you need distinct error handling, then your code should be throwing distinct different kinds of exceptions.

And for the record: I am not saying that there are easy solutions just around the corner. But the one you choose, is as said, more of an anti pattern.

Using Massive Amounts of Implemented Interfaces

I am trying to create a game involving machines and items. I have a simple item interface and every item will implement this.

I would usually just create a class for every item, but there could potentially be thousands of items, and it doesn’t feel right to create thousands of files for all the items. This applies to other large amounts of types of objects I might have. (ground tiles, entities)

I need a type safe way to store all these implemented interfaces. I need to easily be able to create a new item in my code, with only the name of the item.

I was thinking of having a huge class with subclasses holding lots of final constants that would all be anonymous classes, but this also seems like a bad way of doing this.

Is there any good way to do what I have in mind? (Sorry that this is a little vague)

My item interface is currently,

package com.bobona.craftable.model;

import com.bobona.craftable.CraftableGame;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

public interface Item {

    String getId();
    Map<String, Integer> getValues();
    void onUse(AtomicReference<CraftableGame> game, Long entityUsedByIndex);
    void onSecondaryUse(AtomicReference<CraftableGame> game, Long 
    entityUsedByIndex);
}

Solution:

This is a difficult design problem, and there is no one size fits all answer as far as I know. As mentioned by Makoto in another answer, much of your approach will be dictated by the actual details of your specific game.

I would usually just create a class for every item, but there could potentially be thousands of items, and it doesn’t feel right to create thousands of files for all the items.

I completely agree with this statement.

I need a type safe way to store all these implemented interfaces.

I’m not sure that this is possible (literally as written), if we accept the previous statement that separate classes or interfaces aren’t the correct approach. However, if instead of type safe you’ll settle for verifiable at runtime by some yet-unspecified mechanism, then I think it’s quite doable.

[From Comment] It also wouldn’t be nice to use non type-safe values to define items in recipes, as that would quickly become a pain to debug and refactor.

I agree you’ll want some sort of verification, but as previously mentioned full-blown compile-time type safety might not be feasible while also avoiding thousands of separate classes. I think the key here is to reliably detect errors, respond to them in a way that doesn’t break the game, and generate sensible debug messages for the developer.


There are a lot of ways to go about accomplishing this; which one you choose is going to depend on your exact requirements, your preferences, and a number of implementation details that I have no way of knowing. Some things that I think you should look into or consider:

  • Inheritance probably won’t work at all, for the reasons you’ve already identified.
  • Composition or the flyweight pattern might improve things initially, but probably won’t scale the way you want.
  • You could go for a RDBMS approach, as outlined here.
  • You might try a JSON based approach or equivalent, as outlined here.
  • The component pattern fits my understanding of your problem very well.
  • This is an incredibly well written answer detailing how to implement the component pattern for entities (which I think include the types of items you were describing) using bit fields.
  • This is a very similar question to yours on the gamedev stackexchange with some good answers.

Personally I like the component pattern, and am a fan of using JSON or an equivalent language for specifying the items themselves. Hopefully at least some of the above information will help you as you iteratively modify your architecture to meet your gameplay requirements.

Grouping by fields of inner object

I have following two classes:

class Man {
    private int id;
    private String firstName;
    private String lastName;
    private int age;
    private int countOfChildren;
    private Address address; 
}

class Address {
    private Country country;
    private City city;
    private String street;
    private long quantityOfPeople; 
}

I have no idea how to group List<Man> by street and city fields of Address class. How can I do it?

Solution:

Collectors class provides Collectors.groupingBy(keyProvider, downstream) you can use to group by a pair of values. To pair two values you can either use AbstractMap.SimpleEntry or you can implement your own Pair<T,K> class that represents a pair of two values (it’s worth mentioning that you will have to implement hashCode() and equals(object) methods in your Pair class if you want to use it as a key in a hash map). Also two values you want to pair in a key have to implement hashCode() and equals(object) methods – it’s worth using immutable classes in this case.

The whole grouping part can be done by:

final Map<Map.Entry<City, String>, List<Man>> groupedByCityAndStreet = people.stream()
        .collect(Collectors.groupingBy(
                man -> new AbstractMap.SimpleEntry<>(man.getAddress().getCity(), man.getAddress().getStreet()),
                Collectors.toList()
        ));

In this example I have used AbstractMap.SimpleEntry to represent a pair of Country and street. It creates a map where for each key it groups a list of Man object based of country and street. Below you can find a full example:

import java.util.AbstractMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class GroupByTest {

    public static void main(String[] args) {
        final List<Man> people = Arrays.asList(
                new Man(1, "John", "Doe", 20, 0, new Address(new Country("England"), new City("London"), "Test Street 2", 10000)),
                new Man(2, "Mary", "Smith", 54, 4, new Address(new Country("Germany"), new City("Berlin"), "Maine Strasse 32", 10000)),
                new Man(3, "James", "Rose", 13, 0, new Address(new Country("England"), new City("London"), "Test Street 2", 10000)),
                new Man(4, "Vincent", "Dog", 43, 2, new Address(new Country("Germany"), new City("Berlin"), "Volkswagen Platz 31", 10000)),
                new Man(5, "Arnold", "Smoke", 72, 3, new Address(new Country("Italy"), new City("Rome"), "Pepperoni 31", 10000)),
                new Man(6, "Katy", "Puppet", 33, 3, new Address(new Country("England"), new City("London"), "Test Street 3", 10000))
        );

        final Map<Map.Entry<City, String>, List<Man>> groupedByCityAndStreet = people.stream()
                .collect(Collectors.groupingBy(
                        man -> new AbstractMap.SimpleEntry<>(man.getAddress().getCity(), man.getAddress().getStreet()),
                        Collectors.toList()
                ));

        // Print people associated with given city and street to console
        groupedByCityAndStreet.forEach((k, v) -> {
            System.out.println("People associated with " + k.getKey().name + ", " + k.getValue() + ":");
            v.forEach(man -> {
                System.out.println(man);
            });
        });
    }

    static final class Man {
        private final int id;
        private final String firstName;
        private final String lastName;
        private final int age;
        private final int countOfChildren;
        private final Address address;

        public Man(int id, String firstName, String lastName, int age, int countOfChildren, Address address) {
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.countOfChildren = countOfChildren;
            this.address = address;
        }

        public int getId() {
            return id;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public int getAge() {
            return age;
        }

        public int getCountOfChildren() {
            return countOfChildren;
        }

        public Address getAddress() {
            return address;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Man man = (Man) o;
            return id == man.id &&
                    age == man.age &&
                    countOfChildren == man.countOfChildren &&
                    Objects.equals(firstName, man.firstName) &&
                    Objects.equals(lastName, man.lastName) &&
                    Objects.equals(address, man.address);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id, firstName, lastName, age, countOfChildren, address);
        }

        @Override
        public String toString() {
            return "Man{" +
                    "id=" + id +
                    ", firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    ", age=" + age +
                    ", countOfChildren=" + countOfChildren +
                    ", address=" + address +
                    '}';
        }
    }

    static class Address {
        private final Country country;
        private final City city;
        private final String street;
        private final long quantityOfPeople;

        public Address(Country country, City city, String street, long quantityOfPeople) {
            this.country = country;
            this.city = city;
            this.street = street;
            this.quantityOfPeople = quantityOfPeople;
        }

        public Country getCountry() {
            return country;
        }

        public City getCity() {
            return city;
        }

        public String getStreet() {
            return street;
        }

        public long getQuantityOfPeople() {
            return quantityOfPeople;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Address address = (Address) o;
            return quantityOfPeople == address.quantityOfPeople &&
                    Objects.equals(country, address.country) &&
                    Objects.equals(city, address.city) &&
                    Objects.equals(street, address.street);
        }

        @Override
        public int hashCode() {

            return Objects.hash(country, city, street, quantityOfPeople);
        }

        @Override
        public String toString() {
            return "Address{" +
                    "country=" + country +
                    ", city=" + city +
                    ", street='" + street + '\'' +
                    ", quantityOfPeople=" + quantityOfPeople +
                    '}';
        }
    }

    static class City {
        private final String name;

        public City(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            City city = (City) o;
            return Objects.equals(name, city.name);
        }

        @Override
        public int hashCode() {

            return Objects.hash(name);
        }

        @Override
        public String toString() {
            return "City{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    static class Country {
        private final String name;

        public Country(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Country country = (Country) o;
            return Objects.equals(name, country.name);
        }

        @Override
        public int hashCode() {

            return Objects.hash(name);
        }

        @Override
        public String toString() {
            return "Country{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}

When you run this example you will something like this in the console:

People associated with Rome, Pepperoni 31:
Man{id=5, firstName='Arnold', lastName='Smoke', age=72, countOfChildren=3, address=Address{country=Country{name='Italy'}, city=City{name='Rome'}, street='Pepperoni 31', quantityOfPeople=10000}}
People associated with London, Test Street 3:
Man{id=6, firstName='Katy', lastName='Puppet', age=33, countOfChildren=3, address=Address{country=Country{name='England'}, city=City{name='London'}, street='Test Street 3', quantityOfPeople=10000}}
People associated with Berlin, Volkswagen Platz 31:
Man{id=4, firstName='Vincent', lastName='Dog', age=43, countOfChildren=2, address=Address{country=Country{name='Germany'}, city=City{name='Berlin'}, street='Volkswagen Platz 31', quantityOfPeople=10000}}
People associated with Berlin, Maine Strasse 32:
Man{id=2, firstName='Mary', lastName='Smith', age=54, countOfChildren=4, address=Address{country=Country{name='Germany'}, city=City{name='Berlin'}, street='Maine Strasse 32', quantityOfPeople=10000}}
People associated with London, Test Street 2:
Man{id=1, firstName='John', lastName='Doe', age=20, countOfChildren=0, address=Address{country=Country{name='England'}, city=City{name='London'}, street='Test Street 2', quantityOfPeople=10000}}
Man{id=3, firstName='James', lastName='Rose', age=13, countOfChildren=0, address=Address{country=Country{name='England'}, city=City{name='London'}, street='Test Street 2', quantityOfPeople=10000}}

Hope it helps.

(Java) alphabetic substring comparison ends up with a wrong result

In one of these HackerRank Java challenges, there is a problem which is defined as:

The problem

We define the following terms:

  • Lexicographical Order, also known as alphabetic or dictionary order, orders characters as follows: A < B < …< Y < Z < a < b
    … < y < z

  • A substring of a string is a contiguous block of characters in the string. For example, the substrings of abc are a, b, c, ab, bc, and abc.

Given a string, s, and an integer, k, complete the
function so that it finds the lexicographically smallest and
largest substrings of length k.

Here is my (not fully working) solution:

My code

import java.util.*;

public class stringCompare {

    public static String getSmallestAndLargest(String s, int k) {
        String smallest, largest, temp;

        /* Initially, define the smallest and largest substrings as the first k chars */
        smallest = s.substring(0, k);
        largest = s.substring(0, k);

        for (int i = 0; i <= s.length() - k; i++) {
            temp = s.substring(i, i + k);
            for (int j = 0; j < k; j++) {

                /* Check if the first char of the next substring is greater than the largest ones' */
                if (temp.charAt(j) > largest.charAt(j)) {
                    largest = s.substring(i, i + k);
                    break;      
                }

                /* Check if the first char of the next substring is less than the smallest ones' */
                else if (temp.charAt(j) < smallest.charAt(j)) {
                    smallest = s.substring(i, i + k);
                    break;
                } 

                /* Check if the first char of the next substring is either equal to smallest or largest substrings' */
                else if (temp.charAt(j) == smallest.charAt(j)
                        || temp.charAt(j) == largest.charAt(j)) {
                    // If so, move to the next char till it becomes different
                } 

                /* If the first of char of the next substring is neither of these (between smallest and largest ones')
                    skip that substring */ 
                else {
                    break;
                }
            }
        }

        return smallest + "\n" + largest;
    }

    public static void main(String[] args) {
        String s;
        int k;
        try (Scanner scan = new Scanner(System.in)) {
            s = scan.next();
            k = scan.nextInt();
        }

        System.out.println(getSmallestAndLargest(s, k));
    }
}

According to the HackerRank, this code fails for 2 out of 6 cases. One is as follows:

ASDFHDSFHsdlfhsdlfLDFHSDLFHsdlfhsdlhkfsdlfLHDFLSDKFHsdfhsdlkfhsdlfhsLFDLSFHSDLFHsdkfhsdkfhsdkfhsdfhsdfjeaDFHSDLFHDFlajfsdlfhsdlfhDSLFHSDLFHdlfhs
30

The expected output is:

ASDFHDSFHsdlfhsdlfLDFHSDLFHsdl
sdlkfhsdlfhsLFDLSFHSDLFHsdkfhs

But mine becomes:

DFHSDLFHDFlajfsdlfhsdlfhDSLFHS
sdlkfhsdlfhsLFDLSFHSDLFHsdkfhs

At debug mode, I found that the smallest substring was correct until the 67th iteration (i). I don’t know why it changes to a wrong one at that step but it does.

Can anyone help me on that, please?

Thanks!

Solution:

I propose a simple optimisation: a quick peek at the first characters.

largest = smallest = s.substring(0, k);
for (int i = 1; i <= s.length() - k; i++) {
    if (s.charAt(i) > largest.charAt(0) ){
      largest = s.substring(i, i + k);
      continue;
    }
    if (s.charAt(i) < smallest.charAt(0) ){
      smallest = s.substring(i, i + k);
      continue;
    }

    if (s.charAt(i) == largest.charAt(0) ){
        String temp = s.substring(i, i + k);
        if( temp.compareTo(largest) > 0) {
            largest = temp;
            continue;
        }
    }
    if (s.charAt(i) == smallest.charAt(0) ){
        String temp = s.substring(i, i + k);
        if( temp.compareTo(smallest) < 0) {
            smallest = temp;
        }
    }
}

For the example, comparisons drop from 222 to 14.

Parameter type of method to correspond to inner class which extends super's inner class

I have some classes structured as follows:

class A {
    inner class B {}

    void func(B param) {}
}

class Asub extends A {
    inner class B extends A.B {}

    @Override
    void func(B param) {}      // problematic line
}

But the compiler doesn’t allow it as a proper override and only allows it if I change (in Asub)

void func(B param)

to

void func(A.B param)

However I do not want to do that as I have some overriden functionality defined in Asub.B that I want to make use of but if I change the param type to A.B instead of B, the linter tells me that Asub.B is unused

I would appreciate any help in solving this issue or if it is not possible, a possible alternate approach to accomplish the functionality that I want

The actual context of this question has to do with Android RecyclerView.Adapters and ViewHolders but I don’t think the problem resides there

Solution:

I believe your best shot here is using generics.

Something along the lines of

abstract class A<T extends A.B> {
    class B {
      // ...
    }

    abstract void func(T param) {
      //..
    }
}

class Asub<Asub.B> extends A {
    class B extends A.B {
      // ...
    }


    @Override
    void func(Asub.B param) {
      // ...
    }
}

should probably do the job.

Instantiating a class does not work, constructor parameter did not pass

I tried to initialize an circle object from my test class, but the parameter(5.5) did not pass. The result is wrong. I tried to debug and find out the radius is 0.00 in circle class, 5.5 did not pass into the Circle class.
Anyone can help me with that?

This is my output:

The area of circle is:  3.14

This is my test class:

public class ShapeTest {
        public static void main(String[] args){
            Circle circle = new Circle(5.5);
            System.out.println(circle);
            }


        }
    }

This is my circle class:

public class Circle extends TwoDimensionalshape {
        private double radius;

        public Circle(double radius){
            super(radius);
        }

    public void setRadius(double radius){
        this.radius = radius;
    }
    public double getRadius(){
        return radius;
    }

    @Override
    public double getArea(){
        return 3.14+getRadius()+getRadius();
    }

    @Override
    public String toString(){
        return String.format("%s %,.2f%n ","The area of circle is: ",getArea());
    }



}

This is my super class:

public class TwoDimensionalshape implements Area{
        private double radius;
        private double base;
        private double height;

        public TwoDimensionalshape(double radius){
            this.radius = radius;
    }

    public TwoDimensionalshape(double base, double height){
        this.base = base;
        this.height = height;
    }

    public double getRadius() {
        return radius;
    }


    public double getBase() {
        return base;
    }

    public double getHeight() {
        return height;
    }

    @Override
    public double getArea(){
        return 1;
    }

    public String toString(){
        return "The area is: "+getArea();
    }


}

Solution:

Your radius variable in Circle hides the radius variable in TwoDimensionalshape. They are 2 different variables. Your constructor sets the one in TwoDimensionalShape, but getArea is using the one in Circle.

Remove the radius variable in Circle. Let Circle inherit getRadius by removing that method from Circle. Also in Circle, move setRadius to TwoDimensionalShape.

Also, in getArea, multiply the radius twice instead of adding it twice. You can also use Math.PI instead of 3.14.

return Math.PI * getRadius() * getRadius();

How to handle unsigned shorts/ints/longs in Java

I’m reading a file format that specifies some types are unsigned integers and shorts. When I read the values, I get them as a byte array. The best route to turning them into shorts/ints/longs I’ve seen is something like this:

ByteBuffer wrapped = ByteBuffer.wrap(byteArray);
int x = wrapped.getInt();

That looks like it could easily overflow for unsigned ints. Is there a better way to handle this scenario?

Update: I should mention that I’m using Groovy, so I absolutely don’t care if I have to use a BigInteger or something like that. I just want the maximum safety on keeping the value intact.

Solution:

A 32bit value, signed or unsigned, can always be stored losslessly in an int*. This means that you never have to worry about putting unsigned values in signed types from a data safety point of view.

The same is true for 8bit values in bytes, 16bit values in shorts and 64bit values in longs.

Once you’ve read an unsigned value into the corresponding signed type, you can promote them to signed values of a larger types to more easily work with the intended value:

Since there’s no primitive type larger than long, you can either go via BigInteger, or use the convenience methods on Long to do unsigned operations:


* This is thanks to the JVM requiring integer types to be two’s complement.

How to join two Optional<String> with a delimiter in Java 8

I have two Optional strings, name1 and name2. I want to join the two such that the result is also an Optional with:

  1. If either one is non-empty, the result should be the non-empty name.
  2. If both are non-empty, I want the result to be joined with the delimiter AND.
  3. If both are empty, the result should be an empty Optional

My attempt at this:

StringBuilder sb = new StringBuilder();
name1.ifPresent(sb::append);
name2.ifPresent(s -> {
    if (sb.length() > 0) {
        sb.append(" AND ");
    }
    sb.append(s);
}
Optional<String> joinedOpt = Optional.ofNullable(Strings.emptyToNull(sb.toString()));

This works, but seems ugly and not very functional.

PS: There is a similar question but the accepted answer is wrong. Specifically, if name1 is empty and name2 is not, it returns an empty optional.

Solution:

One solution is to stream and reduce():

Optional<String> joinedOpt = Stream.of(name1, name2)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .reduce((a, b) -> a + " AND " + b);

Feel free to replace the filter/map combo with Java 9 or Guava as others have suggested.

How to use Suppliers.memoize when method throws Checked-Exception

I’m trying to use Suppliers#memorize on a function that throws IOException

Snippet:

private Supplier<Map> m_config = Suppliers.memoize(this:toConfiguration);

This gives an exception:
Unhandled exception type IOException

so I had to do something like this:

public ClassConstructor() throws IOException
{
   m_config = Suppliers.memoize(() -> {
   try
   {
     return toConfiguration(getInputFileName()));
   }
   catch (IOException e)
   {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 });

 if(m_Configuration == null) {
   throw new IOException("Failed to handle configuration");
 }
}

I would like the CTOR to forward the IOException to the caller.
The proposed solution is not so clean, is there a better way to handle this situation?

Solution:

Use UncheckedIOException

You’re tagging , so you should use the UncheckedIOException which is present for this very use case.

/**
 * @throws java.io.UncheckedIOException if an IOException occurred.
 */
Configuration toConfiguration(String fileName) {
  try {
    // read configuration
  } catch (IOException e) {
    throw new java.io.UncheckedIOException(e);
  }
}

Then, you can write:

m_config = Suppliers.memoize(() -> toConfiguration(getInputFileName()));