2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javaメモ

Last updated at Posted at 2018-03-09

備忘用。

#Java

StreamAPI

// In: List<SalesLine>
// Out: 商品コードをキー、販売数合計を値とするマップ
Map<String, Integer> map =
        list.stream().collect(
                Collectors.groupingBy(SalesLine::getProductCode,
                        Collectors.summingInt(SalesLine::getQuantity)
                ));

全角・半角変換など

Normalizer.normalize(q, Normalizer.Form.NFKC);

NUL文字による文字列化→分割

String messages = errors.getAllErrors().stream().map(e -> e.getDefaultMessage()).collect(Collectors.joining(new String(new char[] {0}) ));
List<String> list = messages.split(new String(new char[] {0}));

BigDecimalの小数点以下桁数丸め(カリー)

Predicate<Object> isNull = Objects::isNull;
IntFunction<Function<RoundingMode, Function<BigDecimal, BigDecimal>>> setScale = i -> r -> n -> ((BigDecimal) isNull.test(n) ? BigDecimal.ZERO : n)).setScale(i, r);

3桁カンマ付与

Predicate<Object> isNull = Objects::isNull;
Predicate<Object> isNumber = obj -> obj instanceof Number;
final Function<Object, String> addComma = obj -> {
    if (isNull.or(isNumber.negate()).test(obj)) {
        return null;
    }
    if (obj instanceof BigDecimal) {
        return String.format("%,d", ((BigDecimal) obj).longValueExact());
    }
    return String.format("%,d", obj);
};

数値型のゼロ判定

Predicate<Object> isNull = Objects::isNull;
Predicate<Object> isNumber = obj -> obj instanceof Number;
Predicate<Object> isNumberZero = obj -> {
    if (isNull.or(isNumber.negate()).test(obj)) {
        return false;
    }
    if (obj instanceof BigDecimal) {
        return BigDecimal.ZERO.compareTo((BigDecimal) obj) == 0;
    }
    return Objects.equals((long) obj, 0L);
};

Map内のBigDecimalをサマる

hogeMap.merge("key1", BigDecimal.ONE, (BigDecimal sum, BigDecimal val) -> sum.add(val));

BigDecimalへ変換

private BigDecimal toBigDecimal(final Object n) {
    if (Objects.isNull(n)) {
        return BigDecimal.ZERO;
    }
    if (n instanceof java.lang.String) {
        return new BigDecimal((String) n);
    }
    else if (n instanceof Number) {
        return BigDecimal.valueOf((Long) n);
    }
    return BigDecimal.ZERO;
}

オブジェクト不一致判定用

BiPredicate<Object, Object> isNotEquals = ((BiPredicate<Object, Object>)Objects::equals).negate();

DeepCopy

java.util.ArraysによるDeepCopy

int[] copySrc = new int[5];
Arrays.fill(copySrc, 0);
int[] copyDst = Arrays.copyOf(copySrc, copySrc.length);

オブジェクトのDeepCopy

org.apache.commons.lang3.SerializationUtils#cloneによるDeepCopy

public Object deepCopy(Serializable state) {
  return SerializationUtils.clone(state);
}

優先度付きキュー - PriorityQueue

いまいち有効な使い方がわからん。
AtCoder Regular Contest 028 - B - 特別賞を解くのに役立つらしい。

PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
pQueue.offer(i);    // 追加
pQueue.peek(i);     // 取得(キューから削除しない)
pQueue.poll(i);     // 取得(キューから削除する)

@see ダイクストラ法

オブジェクトの中身を表示

// commons-lang
System.out.println(ToStringBuilder.reflectionToString(new Hoge()));
// hoge$Hoge@cafb56[id=1,value=hoge,strValues={aaa,bbb,ccc},items=[ddd, eee, fff]]

オブジェクトにハッシュコードを付与

public class Clazz implements Serializable {
  private static final long serialVersionUID = 1L;
  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
  }
}

オブジェクトの一致判定を簡単に書けるよ

public class Hoge implements Serializable {
    private static final long serialVersionUID = 1L;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
}

区分値判定

Enum使いなさいよ。ですよね~

if ( Arrays.asList("Cat", "Dog", "Pig").contains(hoge) ) {
  // Do somthings.
}

Listの初期化

List<String> list = new ArrayList<>(Arrays.asList("Cat", "Dog", "Pig"));

ファイル名の昇順ソート

// ファイル名 昇順にソート
List<File> csvFileList = new ArrayList<File>();
csvFileList.add( new File("###") );
csvFileList.add( new File("BBB") );
csvFileList.add( new File("111") );
csvFileList.add( new File("AAA") );

Collections.sort( csvFileList, new Comparator<File>(){
   @Override
   public int compare( File o1, File o2 ) {
       return StringUtils.compare( o1.getName(), o2.getName() );
   }
});

IterableUtils.forEach( csvFileList, new Closure<File>(){
   @Override
   public void execute( File file ) {
       System.out.println( ReflectionToStringBuilder.toString( file ) );
   }
});

Spring

リソースファイル取得

@Autowired
ResourceLoader resourceLoader;

final Resource resource = resourceLoader.getResource("classpath:path/to/file");

BindingResultのメッセージをString配列にする

# org.springframework.validation.BindingResult errors;
setMessages(errors.getAllErrors().stream().map(e -> e.getDefaultMessage()).toArray(String[]::new));
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?